什么是组件?
组件是可复用的 Vue 实例。
为什么要使用组件?
使用组件能将项目按功能模块或页面层级拆分得更细小,更易于维护。
组件的定义分为几种?
两种
- 全局注册
- 局部注册
如何全局注册组件
使用 Vue.component 方法
Vue.component('hello', {
data: function() {
return {
msg: '张三'
}
},
template: `
<div>{{ msg }}</div>
`
})
如何局部注册组件
在需要使用这个组件的组件中或根实例中,使用 components 选项
new Vue({
el: '#app',
components: {
helloWorld: {
data: function() {
return {
msg: '张三'
}
},
template: `
<div>{{ msg }}</div>
`
}
}
})
如何使用组件
把组件的名字作为自定义元素来使用即可
PS
- 组件的名称不要与现有标签或现有组件重名
- 组件的
template
选项需要有一个根元素,且只能有一个根元素 - 组件的
data
选项需要时一个函数,在函数中返回一个对象 - 全局注册组件,必须写在
new Vue
之前 - 如果组件的名字是 驼峰 命名方式,那么使用的时候需要为 短横线 方式
new Vue({
el: '#app',
components: {
helloWorld: {
data: function() {
return {
msg: '张三'
}
},
template: `
<div>{{ msg }}</div>
`
}
}
})
<div id="app">
<hello-world></hello-world>
</div>
- 上面的第五点中,如果使用组件的时候是在如下的环境中,则可以不用。
- 字符串 (例如:
template: '...'
) - 单文件组件 (
.vue
) <script type="text/x-template">
网友评论