组件注册(Vue2笔记)

127 阅读2分钟

组件基础

组件是可复用的Vue实例

为了能在模板中使用,组件必须先注册以便Vue能够识别,有两种注册类型:全局注册和局部注册
全局注册:

Vue.component('my-component-name', {  
//options
})

通过 Prop 向子组件传递数据

prop是可以在组件上注册的一些自定义的attribute。当一个值传递给一个prop attribute 的时候,它就变成了那个组件实例的一个property

在组件上使用v-model

<input v-model="searchText">

等价于:

<input  
v-bind:value="searchText"  
v-on:input="searchText = $event.target.value"  
>

组件注册

组件名

组件名大小写

定义组件名的方式有两种:

  • kebab-case
Vue.component('my-component-name', { /* ... */ })
  • PascalCase
Vue.component('MyComponentName', { /* ... */ })

PascalCase在<my-component-name> 和 <MyComponentName> 都是可接受的,但是直接在DOM中使用只有短横线分隔命名是有效的

全局注册

使用Vue.component来创建组件:

Vue.component('my-component-name', {  
 // ... 选项 ...  
})

它们在注册之后可以用在任何新创建的Vue跟实例(new Vue)的模板中,比如:

Vue.component('component-a', { /* ... */ })  
Vue.component('component-b', { /* ... */ })
new Vue({ el: '#app' })
    <div id="app">
      <component-a></component-a>
      <component-b></component-b>
    </div>

在所有的子组件中也是如此,也就是说这两个组件在各自内部也都可以相互使用。

局部注册

可以通过一个普通的javascript对象来定义组件:

var ComponentA = {/* ... */}
var ComponentB = { /* ... */ }  
var ComponentC = { /* ... */ }

然后在components选项中的定义想使用的组件:

    new Vue({
      el: '#app',
      components: {
        'component-a': ComponentA,
        'component-b': ComponentB
      }
    })

对于components对象中的每个property来说,其property名就是自定义元素的名字,其property值就是这个组件的选择对象。

局部注册的组件在其子组件不可用。如果希望在子组件中可用,可以这样写:

var ComponentA={/* ... */}
var ComponentB={
   components:{
      'component-a':ComponentA
    }
  }

模块系统

在模块系统中局部注册

在一个假设的ComponentB.js或ComponentB.vue文件中:

import ComponentA from './ComponentA'  
import ComponentC from './ComponentC'  
  
export default {  
components: {  
ComponentA,  
ComponentC  
},  
// ...  
}