父組件傳值給子組件
這裏涉及$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)
},