使用组件的原因是提高代码复用性。
组件的使用方法
组件需要先注册才能使用,注册分为全局注册和局部注册两种。 全局注册:
Vue.component('component-name',{
template:'<div>内容</div>'
})
在html中以component-name为标签就会用template中的内容替换<component-name>.
局部注册:
var app = new Vue({
el:'#app',
data:{
},
components:{
'part-ponents':{
template:"<div>我是局部注册</div>"
}
}
})
- 局部注册的组件只能在本个Vue实例中使用。
像li ul table td th等适用场合有限制,会导致我们的组件失效。解决办法如下:
<table>
<th is="my-component"></th>
</table>
使用组件的技巧
- 是用小写字母加"-"来命名。
- template中的内容必须使用html标签包裹。
- 在组件的定义中,除template外还可以有data,computed,methods,其中 data必须是一个方法。
父向子组件传递数据
- 在组件中使用props从父亲组件接收参数。在props中定义的属性都可以直接在组件中直接使用。
- props的值有两种,一种是字符串数组,一种是对象。 来一个示例吧:
<div id="app">
<part-component msg="久在樊笼里,复得返自然。"></part-component>
</div>
var app = new Vue({
el:'#app',
data:{
},
components:{
'part-components':{
props:['msg']
template:'<div>{{msg}}</div>'
}
}
})
<div id="app">
<input type="text" v-model='parent'>
<pcomponnet :msg="parent"></pcomponent>
<div>
var app = new Vue({
el:"#app",
data:{
parent:'少无适俗韵'
},
components:{
'pcomponent':{
props:['msg']
template:<div>{{msg}}</div>
}
}
})
单向数据流
定义:通过 prop 传输数据的时候,可以通过父组件向子组件传输数据,反过来是不行的,以避免子组件影响父组件。
应用场景:
1.
<div id='app'>
<my-component msg='开荒南野际'></div>
</div>
var app = new Vue({
el:'#app',
components:{
'my-component':{
template:'<div>{{count}}</div>',
data:function(){
return{
count: this.msg
}
}
}
}
})
<input v-model="width" type="text"></input>
<width-component></width-component>
var app = new Vue({
el: '#app',
data: {
width: 0
},
components: {
'width-component': {
template: '<div :style="style"></div>',
computed: {
style: function(){
return {
width: this.$parent.$data.width + 'px',
'background-color': 'red',
height: '30px'
}
}
}
}
}
})
数据验证
数据类型校验
<div id="app">
<my-component :a='a' :b='b' :c='c' :d='d' :e='e'></my-component>
</div>
Vue.component('my-component',{
props:{
a:Number //数据类型验证,是否为数字
b:[Boolean,String] //验证数据类型是否为布尔值或者字符串。
c:{
type:Boolean,
default:true,
required:true
},
d: { //父组件未向子组件传数据时使用默认值
type: Array,
default: function () {
return 123
}
},
e: { //开发环境构建版本会提示错误
validator: function (value) {
return value < 10;
}
}
},
template:'<div>{{a}}--{{b}}--{{c}}--{{d}}</div>'
})
var app = new Vue({
el:'#app',
data:{
a:1,
b:true,
c:'',
d: [],
e: 111
}
})