如题,我想要在vue父组件中监听子组件的数据变化,当数据变化的时候,触发父组件相应的函数。
以下仅为示意代码,并非项目源码,根据项目实际情况,请勿使用 $emit以及vuex来实现通信
父组件:
<template>
<div class="parent">
<child-component ref="child"></child-component>
<div class="tips">这里是父组件的数据:{{a}}</div>
</div>
</template>
<script>
import ChildComponent from "./ChildComponent.vue"
export default{
name: 'ParentComponent',
computed:{
a:{
get(){
this.fn(this.$refs.child.a);
return this.$refs.child.a;
}
}
},
methods:{
fn(val){
alert(val);
}
},
}
</script>
子组件:
<template>
<div class="child">
<div class="btn" @click="add">+1</div>
<div class="tips">这里是子组件的数据:{{a}}</div>
</div>
</template>
<script>
import ChildComponent from "./ChildComponent.vue"
export default{
name: 'ParentComponent',
data(){
return{
a: 0
}
},
methods:{
add(){
this.a ++;
}
},
}
</script>
求各位支招解决,谢谢。
通过父组件通过 props把数据传给子组件,子组件改变
父组件每次传一个对象给子组件, 对象之间引用