vue最强大的功能之一,扩展html元素,封装代码。 语法:
Vue.component(tagName, options)
之后就可以在html中<tagName></tagName>来使用它。 自定义组件也分为全局和局部两种,全局可以在任何实例中使用,而局部只有注册后才能使用。 全局:
<body>
<div id="app">
<test></test>
</div>
</body>
<script>
Vue.component('test',{
})
new Vue({
el : '#app'
})
</script>
运行后从控制台可以看见报错信息。
[Vue warn]: Failed to mount component: template or render function not defined.
所以如果就这样空着不能算是写完,至少需要在里面写一个template属性,来渲染里面的信息。
Vue.component('test',{
template : '<h1>test</h1>'
})
之后再运行就可以看见结果。 局部: 使用VUe.定义components为全局,如果在vue实例里面定义想要的组件说明是局部
var test = {
template : '<h1>test</h1>'
}
new Vue({
el : '#app',
components:{
'test' : test
}
})
除了template属性,还有其他属性: Prop 可以用来接收自定义属性,正常态是json数组
<div id="app">
<test message="ttt"></test>
</div>
Vue.component('test',{
props : ['message'],
template : '<h1>{{ message }}</h1>',
})
如果使用v-bind就可以实现动态获取
<div id="app">
<input type="test" v-model="tworld" />
<test :message="tworld"></test>
</div>
Vue.component('test',{
props : ['message'],
template : '<h1>{{ message }}</h1>',
})
var vm = new Vue({
el : '#app',
data : {
tworld : '这是测试'
}
})
以上是prop传入json数组的正常态 如果prop传入的是一个对象而不是字符串数组的时候,它就能进行验证。 主要作用是可以进行一个预先检查,避免出现预料之外的错误
<div id="app">
<test :message="tworld"></test>
</div>
Vue.component('test',{
props : {
'message' : Number
},
template : '<h1>{{ message }}</h1>',
})
如果message接受到的值不是number类型了话控制台就会报错
[Vue warn]: Invalid prop: type check failed for prop "message". Expected Number, got String.
found in
---> <Test>
<Root>
就可以避免在开发过程中乱传变量类型。