组件是 Vue.js 最强大的功能之一,组件可以扩展 HTML 元素,封装可重用的代码。组件系统让我们可以用独立可复用的小组件来构建大型应用,几乎任意类型的应用的界面都可以抽象为一个组件树:



在编写组件时,我们需要不断思考如何提高组件的可复用性。

组件是可复用的 Vue 实例, 我们可以把页面中在多个场景中重复使用的部分,抽出为一个组件进行复用。组件大大提高了代码的复用率。

全局组件注册

我们可以通过调用 Vue.component 的方式来定义全局组件,它接收两个参数:

  1. 组件名,
  2. 组件属性对象。

属性对象:组件的属性对象即为 Vue 的实例对象属性。

全局组件可以在任何其他组件内使用,所以当我们设计的组件,需要在不同地方使用的时候,我们应当注册全局组件。

 // 注 册
 // 驼峰命名
 Vue.component('MyComponentName', { /* */ })
 // 短横线命名
 Vue.component('my-component-name', { /* */ })
 ......
 // 使 用
 <my-component-name> < /my-component-name>
 // 也可以使用自闭和的方式
 <my-component-name />

具体示例如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Document</title>
</head>

    <div>
        <my‐component></my‐component>
        <my‐component/>
    </div>

</html>

代码解释:

JS 代码第 3-5 行,我们注册了一个全局组件 myComponent,并在 html 内使用两种方式引用了该组件。

局部组件注册

我们也可以在 Vue 实例选项中注册局部组件,这样组件只能在这个实例中使用。

局部组件的注册利用 Vue 实例的 components 对象属性,以组件名作为 key 值,以属性对象作为 value。

由于局部组件只能在当前的 Vue 实例中使用, 所以当我们设计的组件不需要在其他组件内复用时,可以设计为局部组件。

//注册
components: {
'MyComponentName': {
template: '<div>Hello !</div>'
}
}
......
// 使 用
<my‐component‐name></my‐component‐name>
// 也可以使用自闭和的方式
<my‐component‐name/>

具体示例如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Document</title>
</head>
    <div>
        <my‐component></my‐component>
        <my‐component/>
    </div>
</html>