Vue父子组件通讯传值
父组件往子组件传值
<body>
<div id="App">
<child :txt="msg"></child>
<child txt="txt的属性值"></child>
<child></child>
</div>
<script>
Vue.component("child",{
template: "<p>{{txt}}</p>",
props: {
txt: {
default: "组件自带的默认值"
}
}
})
let app = new Vue({
el: "#App",
data: {
msg: "组件传值"
}
})
</script>
</body>
子组件与父组件通信
方式1 采用中间件作为通讯中转站实现子组件往父级组件通讯传值的功能
<body>
<div id="App">
<em>电话次数: {{num}} </em>
<child :txt="msg"></child>
<child txt="txt的属性值"></child>
<child></child>
</div>
<script>
let connectCar = new Vue();
Vue.component("child",{
template: "<p @click='callParent'>{{txt}}</p>",
props: {
txt: {
default: "组件自带的默认值"
}
},
methods: {
callParent(){
connectCar.$emit("call","Child发来信息了");
}
}
})
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>
利用自定义事件实现子组件与父组件通讯
<body>
<div id="App">
<em>电话次数: {{num}} </em>
<child :txt="msg" @call="callChild"></child>
<child txt="txt的属性值" @call="callChild"></child>
<child @call="callChild"></child>
</div>
<script>
let connectCar = new Vue();
Vue.component("child",{
template: "<p @click='callParent'>{{txt}}</p>",
props: {
txt: {
default: "组件自带的默认值"
}
},
methods: {
callParent(){
this.$emit("call","Child发来信息了");
}
}
})
let app = new Vue({
el: "#App",
data: {
msg: "组件传值",
num: 0
},
methods:{
callChild(msg){
console.log(msg);
this.num ++;
}
}
})
</script>
</body>