我理解的组件就是自己封装的html代码块。
vue可以创建全局的组件,也可以创建局部的组件。
如果我们在创建组件时,在其他地方还会用到这一段html代码,我们可以全局创建一个组件:
new Vue({
el: '#aaa',
})
Vue.component('my-component', {
})
其中my-compontent是我们自定义的标签名,{ }里面是我们代码块的内容,将很多个html标签组合,封装起来。
在一个实例的模版中使用,要注意先定义好组件,在创建vue实例。
// 注册
Vue.component('my-component', {
template: '<div>A custom component!</div>'
})
// 创建根实例
new Vue({
el: '#example'
})
渲染为:
<div id="example">
<div>A custom component!</div>
</div>
一个全局的组件就这样封装好了,以后在其他地方就可以复用了。
有时我们并不想要组件的作用域这么大,我们只希望在局部使用这个组件,这样我们就要创建一个局部组件。
var Child = {
template: '<div>A custom component!</div>'
}
new Vue({
components: {
'my-component': Child
}
})
my-component是我么创建的组件名(相当于div、span),
template里面是我们想要封装起来的内容
child是一个中间量
components相当于全局创建的vue.components
在组建中使用某些标签时,vue不能很好的解析,从而出现渲染的问题,其中主要是ol、ul、table、select等内部可以包含其他标签的元素,还有option这种只能出现在特定元素中的标签。
在组建中传入的data标签必须是函数!
var data = { counter: 0 }
Vue.component('simple-counter', {
template: '<button v-on:click="counter += 1">{{ counter }}</button>',
data: function () {
return cunter:0
}
})
new Vue({
el: '#example-2'
})
如果这样写的:
Vue.component('my-component', {
template: '<span>{{ message }}</span>',
data: {
message: 'hello'
}
})
vue则会停止运行,并且警告。