IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> Vue 官方笔记--组件 -> 正文阅读

[JavaScript知识库]Vue 官方笔记--组件

中文版(英文浓缩)

组件是什么?

组件:具有预定义选项实例
组件是一种抽象,允许我们使用小型、独立和通常可复用的组件构建大型应用
通过 prop ,我们可以实现父子组件之间的解耦,有了属性,子组件中就可以使用更为复杂的模板和逻辑,比如如下

<!-- 复制到 html 中可以直接运行哦,看看是什么结果吧 -->
<div id="main">
    <ol>	
        <!-- 子组件 -->
        <todo-item v-for="todo in groceryList" 
                   :key="todo.id" 
                   :todo="todo">
        </todo-item>
    </ol>
</div>
<script src="https://unpkg.com/vue@next"></script>
<script>
    const TodoList = {
        data() {
            return {
                groceryList: [
                    { id: 0, text: 'Vegetables' },
                    { id: 1, text: 'Cheese' },
                    { id: 2, text: 'Meat' }
                ]
            }
        }
    }
    const app = Vue.createApp(TodoList)
    // 父组件       
    // 试想,如果没有定义在父组件中定义 todo 这个属性,该怎样实现同样的功能呢? 不好实现呀
    app.component('todo-item', {
        props: ['todo'],
        template: `<li>{{ todo.text }}</li>`
    })
    app.mount('#main')
</script>

创建应用实例

通过 createApp 函数创建创建了应用实例(application instance),它表明 Vue 应用的开始

这个应用实例未来会通过 mount 函数变成根组件实例,这就是应用实例最终的命运吗?有点科幻色彩~

const app = Vue.createApp(RootComponent)

这个应用实例用来注册一个全局信息,在整个 Vue 应用中的所有组件都可以使用这个全局信息

应用实例相当于一个进程,而组件就相当于一个线程,线程之间可以相互合作,并共享进程的信息

根组件

根组件就是 应用实例 经过 mount() 函数挂载所返回的东西(如app.mount('#app')返回的就是根组件)

传递给 createApp 函数的选项是用于配置根组件的,比如

const RootComponent = { 
    // data() 函数是用于配置根组件的其中之一的选项,此外还有 methods()、computed() 等
    data() {
        return {
            a: 123
        }
    }
}
// RootComent 用于配置根组件,虽然根组件是调用 mount() 才返回的,但是就好像提前占一个坑,预定一样 
const app = Vue.createApp(RootComponent)
const vm = app.mount('#app')

当我们为我们的应用实例使用 mount 方法(即挂载)时,表明这个应用实例(此时应该是根组件了)被用作渲染的起点

应用实例调用方法(除了mount 方法)后,还是会返回一个应用实例(比如 app 是一个应用实例,调用 app.component( /* xxx */ ) 之后,还是会返回一个应用实例)

但是,mount 方法不会返回应用实例,而是会返回根组件实例

应用实例最终需要挂载到一个 DOM 元素中() 如<div id="app"></div>,于是我们给 mount 传递 #app

mount 内部是这样实现的

const res = document.querySelector('#app')
return res

每个组件都会有自己的组件实例,比如

// 会有一个组件实例
app.component('haha', {
  template: `
    <h1>
      haha
    </h1>`
})

在应用中的组件实例都会共享根组件实例

我们可以在组件实例中添加用户自定义的属性,如methods, props, computed, inject and setup

这些所有的自定义属性都可以在模板中使用,比如

<!-- 可复制直接运行 -->
<div id="main">
    <!-- 在模板中使用了组件实例中的 data() 属性 -->
    {{ a }}
</div>
<script src="https://unpkg.com/vue@next"></script>
<script>
    const app = Vue.createApp({
        data() {
            return {
                a: 123
            }
        },
    })
    app.mount('#main')
</script>

英文原版

what is the Component?

component is an abstraction that allows us to build large-scale applications composed of small, self-contained, and often reusable components.

component :instance with pre-defined options

In Vue, a component is essentially an ??instance with pre-defined options. Registering a component in Vue is straightforward

// Create Vue application
const app = Vue.createApp(...)

// Define a new component called todo-item
app.component('todo-item', {
  template: `<li>This is a todo</li>`
})

// Mount Vue application
app.mount(...)				// mount will returns the root component instance

But this would render the same text for every todo, which is not super interesting. We should be able to pass data from the parent scope into child components. Let’s modify the component definition to make it accept a prop

app.component('todo-item', {
  props: ['todo'],
  template: `<li>{{ todo.text }}</li>`
})

we have managed to separate our app into two smaller units, and the child is reasonably well-decoupled from the parent via the ??props interface. We can now further improve our <todo-item> component with more complex template and logic without affecting the parent app.

In a large application, it is necessary to divide the whole app into components to make development manageable. We will talk a lot more about components later in the guide, but here’s an (imaginary) example of what an app’s template might look like with components:

<div id="app">
  <app-nav></app-nav>
  <app-view>
    <app-sidebar></app-sidebar>
    <app-content></app-content>
  </app-view>
</div>

Creating an Application Instance

Every Vue application starts by creating a new application instance with the createApp function:

// app is a new application instance
const app = Vue.createApp({	
  /* options */
})

The application instance is used to register ‘globals’ that can then be used by components within that application. We’ll discuss that in detail later in the guide but as a quick example:

const app = Vue.createApp({})
// application instance is used by components
app.component('SearchInput', SearchInputComponent)
app.directive('focus', FocusDirective)
app.use(LocalePlugin)

Most of the methods exposed by the application instance return that same instance (chain)

The Root Component

The options passed to createApp are used to configure the root component.

That component is used as the ? 🔰 starting ?point for rendering when we mount the application.

An application needs to be mounted into a DOM element. For example, if we want to mount a Vue application into <div id="app"></div>, we should pass #app

Unlike most of the application methods, mount does not return the application. Instead it ??returns the root component instance.

Although not strictly associated with the MVVM pattern (opens new window), Vue’s design was partly inspired by it.

As a convention, we often use the variable vm (short for ViewModel) to refer to a ??component instance.

While all the examples on this page only need a single component, most real applications are organized into a tree of nested, reusable components. For example, a Todo application’s component tree might look like this:

Root Component
└─ TodoList
   ├─ TodoItem
   │  ├─ DeleteTodoButton
   │  └─ EditTodoButton
   └─ TodoListFooter
      ├─ ClearTodosButton
      └─ TodoListStatistics

Each component will have its own component instance, vm. For some components, such as TodoItem, there will likely be multiple instances rendered at any one time. All of the component instances in this application will share the same application instance.

We’ll talk about the component system in detail later. For now, just be aware that the root component isn’t really any different from any other component. The configuration options are the same, as is the behavior of the corresponding component instance


difference between an instance and an obejct ?

Once you instantiate a class (using new), that instantiated thing becomes an object.

Instance refers to the copy of the object at a particular time whereas object refers to the memory address of the class.

an object represents a set of instances while an instance is a certain, specific representation.

Component Instance Properties

Earlier in the guide we met data properties. Properties defined in data are exposed via the component instance:

const app = Vue.createApp({
  data() {
    return { count: 4 }
  }
})

const vm = app.mount('#app')

console.log(vm.count) // => 4

There are various other component options that add user-defined properties to the component instance, such as methods, props, computed, inject and setup. We’ll discuss each of these in depth later in the guide. All of the properties of the component instance, no matter how they are defined, will be accessible in the component’s template.

Vue also exposes some built-in properties via the component instance, such as $attrs and $emit. These properties all have a $ prefix to avoid conflicting with user-defined property names

Lifecycle Hooks

Each component instance goes through a series of initialization steps when it’s created - for example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes. Along the way, it also runs functions called lifecycle hooks, giving users the opportunity to add their own code at specific stages.

For example, the created hook can be used to run code after an instance is created:

Vue.createApp({
  data() {
    return { count: 1 }
  },
  created() {
    // `this` points to the vm instance
    console.log('count is: ' + this.count) // => "count is: 1"
  }
})

There are also other hooks which will be called at different stages of the instance’s lifecycle, such as mounted, updated, and unmounted. All lifecycle hooks are called with their this context pointing to the current active instance invoking it.

TIP

Don’t use arrow functions (opens new window)on an options property or callback, such as created: () => console.log(this.a) or vm.$watch('a', newValue => this.myMethod()). Since an arrow function doesn’t have a this, this will be treated as any other variable and lexically looked up through parent scopes until found, often resulting in errors such as Uncaught TypeError: Cannot read property of undefined or Uncaught TypeError: this.myMethod is not a function.

  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章      下一篇文章      查看所有文章
加:2021-07-25 11:33:33  更:2021-07-25 11:35:52 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/2 14:50:07-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码