项目中经常会用到父子组件间通信来传值,以达到其中一方的改变可以通知到另一方。比如父组件里有两个子组件A、B,A组件内改变了一个值,需要通知到B组件。
首先父组件需要接收A组件传来的值,这就是子组件向父组件传值。
父组件:
<sidebar-share :theme-type.sync="themeType"> </sidebar-share>
data() {
return {
themeType:'dark'
};
}
A子组件:
<base-switch @input="toggleMode"></base-switch>
methods: {
toggleMode(type) {
if(...){
this.$emit('update:themeType', 'dark');
}
else{
this.$emit('update:themeType', 'light');
}
}
}