Vue父子組件通訊傳值
父組件往子組件傳值
<body>
<div id="App">
<!--可以采用v-bind動(dòng)態(tài)傳值-->
<child :txt="msg"></child>
<!--靜態(tài)值(常量)-->
<child txt="txt的屬性值"></child>
<!--采用默認(rèn)值 前提是有設(shè)置-->
<child></child>
</div>
<script>
// 全局組件
Vue.component("child",{
template: "<p>{{txt}}</p>",
props: {
txt: {
default: "組件自帶的默認(rèn)值"
}
}
})
//props => Object || Array
//組件傳值
let app = new Vue({
el: "#App",
data: {
msg: "組件傳值"
}
})
</script>
</body>
子組件與父組件通信
方式1 采用中間件作為通訊中轉(zhuǎn)站實(shí)現(xiàn)子組件往父級(jí)組件通訊傳值的功能
<body>
<div id="App">
<em>電話次數(shù): {{num}} </em>
<!--可以采用v-bind動(dòng)態(tài)傳值-->
<child :txt="msg"></child>
<!--靜態(tài)值-->
<child txt="txt的屬性值"></child>
<!--采用默認(rèn)值 前提是有設(shè)置-->
<child></child>
</div>
<script>
let connectCar = new Vue();
// 全局組件
Vue.component("child",{
template: "<p @click='callParent'>{{txt}}</p>",
props: {
txt: {
default: "組件自帶的默認(rèn)值"
}
},
methods: {
callParent(){
connectCar.$emit("call","Child發(fā)來(lái)信息了");
}
}
})
//組件傳值
let app = new Vue({
el: "#App",
data: {
msg: "組件傳值",
num: 0
},
methods:{
callChild(){
connectCar.$on("call",msg => {
console.log(msg);
this.num ++;
})
}
}
})
// 建立通信連接
app.callChild();
</script>
</body>
利用自定義事件實(shí)現(xiàn)子組件與父組件通訊
<body>
<div id="App">
<em>電話次數(shù): {{num}} </em>
<!--可以采用v-bind動(dòng)態(tài)傳值-->
<child :txt="msg" @call="callChild"></child>
<!--靜態(tài)值-->
<child txt="txt的屬性值" @call="callChild"></child>
<!--采用默認(rèn)值 前提是有設(shè)置-->
<child @call="callChild"></child>
</div>
<script>
let connectCar = new Vue();
// 全局組件
Vue.component("child",{
template: "<p @click='callParent'>{{txt}}</p>",
props: {
txt: {
default: "組件自帶的默認(rèn)值"
}
},
methods: {
callParent(){
this.$emit("call","Child發(fā)來(lái)信息了");
}
}
})
//組件傳值
let app = new Vue({
el: "#App",
data: {
msg: "組件傳值",
num: 0
},
methods:{
callChild(msg){
console.log(msg);
this.num ++;
}
}
})
</script>
</body>