父组件传值给子组件
这里涉及$emit() :用于子组件给父组件传值
父组件中注册了子组件,将值传递给子组件:
<blog-post title="My journey with Vue"></blog-post>
子组件利用props接收值
export default{
data(){
return {}
},
props: ['title'],
}
//this.$props.title 就能获取到值了哦~
子组件传值给父组件
子组件:
<button @click="toParents()">给父组件传值</button>
//方法
toParents:function(){
this.$emit('parentFun','这是给父组件的值')
}
//可以简写成
<button @click="$emit('parentFun','hhhh')">给父组件传值</button>
父组件:
<HelloWorld :msg.async="msg" @parentFun='change'/> //注册组件的时候进行事件绑定
//方法
change:function(data){
console.log(data)
}
vue2.4+版本后添加了.sync修饰符:可以在子组件中修改值
父组件:
<HelloWorld :msg.sync="msg" @parentFun='change'/> //使用sync修饰符
//在父组件中监听msg是否发生了变化
watch:{
msg:(newValue,oldValue)=>{
console.log(oldValue);
console.log(newValue)
}
},
子组件中:要修改值需要出发函数 update:msg : update是固定的,后面跟着的是变量
changeMsg: function() {
this.$emit('update:msg','hello')
console.log(this.$props.msg)
},