vue设计模式是数据流在组件之间是单向流动,组件内部是数据双向绑定,
父组件一般会通过props绑定数据传递给子组件;
<parent-component :props_data=props_data/>
子组件通过props接受父组件传递过来的值;
<child-component/>
export default{
name:'child-component',
props:['props_data']
data(){
return{
name:'小白'
}
}
}
props基本形式(不能传递对象,只改变了索引,数据会上下都改变,如果传递的是对象的话必须深拷贝,建议再计算属性computed改变)
props设置类型和默认值
props:{
propA: {
type: Number,
default: 100,//默认值是100;
},
propB: {
type: String,
required: true//是否必须传递;
},
}
在组件中直接使用this.propA
父子组件之间方法相互调用
子组件调用父组件的方法
<parent-component @set_data=set_data/>父组件中定义子组件中调用的方法,方法名可以不一样,
<child-component/>
export default{
name:'child-component',
data(){
return{
name:'小白'
}
},
methods:{
onclick(){
this.$emit('set_data',params)//父组件接受子组件的的传递参数
}
},
}
父元素调用子组件的方法
<child-component ref='childModel'/>
methods:{
onclick(){
this.ref['childModel'].$emit('child_mothod',params)
}
}
这种写的话在子组件生命周期中监听就可以了
mounted(){
this.$on('child_mothod',(params)=>{
console.log('调用方法后传递的参数',params)
})
}
methods:{
onclick(){
this.ref['childModel'].child_mothod(params)
}
}
这样写的话在子组件直接方法中直接接受就可以了
methods:{
child_mothod(params){
console.log('父组件传递的参数',params)
}
}
网友评论