Vue关于组件化开发知识点详解
全局组件注册
Vue.component('first-component',{
data:function(){
return{
count:0
}
},
template:''
})
data必须是一个函数
组件模板内容必须是单个根元素
组件模板内容可以是模板字符串
全局组件可以嵌套全局组件
组件命名方式
Vue.component('first-component',{/*....*/})
//普通标签模板中不能使用驼峰,只能在template中使用驼峰方式
Vue.component('firstComponent',{/*....*/})
局部组件注册
局部注册的组件只能在父组件中使用;
varvm=newVue({
components:{
'hello-world':{
data:function(){
return{
msg:'helloworld'
}
},
template:'{{msg}}'
}
}
})
props传递数据原则:单向数据流
组件内部通过props接收传递过来的值
Vue.component('son-com',{
props:['msg','parentMsg']
template:'{{msg+"---"+parentMsg}}'
})
父组件通过属性将值传递给子组件
props属性名规则
- 在props中使用驼峰形式,模板中需要使用短横线的形式;html对大小写的不敏感的
- 字符串中没有这个限制
props传递类型
:boolean="pboolean" :arr="parr" :obj="pobj" >
Vue.component('son-com',{
props:['str','num','boolean','arr','obj'],
template:`
{{str}}
{{num}}
{{boolean}}
{{item}}
{{obj.name}}
{{obj.age}}
`
})
varvm=newVue({
el:'#app',
data:{
pstr:'helloVue',
pnum:12,
pboolean:true,
parr:['apple','banner','orange'],
pobj:{name:'zs',age:22}
}
})
子组件向父组件传值
子组件通过自定义事件向父组件传值$emit()
Vue.component('son-com',{
template:`
传值从第二个参数开始
`
})
父组件监听子组件事件
父组件
varvm=newVue({
el:'#app',
data:{
font:10
},
methods:{
handle:function(val){
this.font+=5
this.font+=val//此时的val就是子组件传递过来的值
}
},
})
非父子组件传值
单独的事件中心管理组件之间的通信
//创建事件中心
varhub=newVue()
//在mounted中监听事件
hub.$on('eventName',fn)
hub.$off('eventName')//销毁事件
//在methods中处理事件
hub.$emit('eventName',param)
组件插槽
程序错误 我是没有匹配的内容匹配页脚一次
匹配页脚两次
Vue.component('tmp-com',{
template:`
如果上面没有匹配到对应的标签就会展示默认内容
`
})
到此这篇关于Vue关于组件化开发知识点详解的文章就介绍到这了,更多相关Vue组件化开发内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!