Vue-provide-inject
子组件要改变父组件的数据
父组件中
provide(){
return {
themName: this.themName
};
},
data(){
return {
themName: "blue",
fontSize: "normal"
};
},
上面的provide就把themName提供给别人了,不过themName是字符串,不是对象数组这些提供引用,外面改了是没有用的,因为是提供了复制的字符串。
子组件中
inject: ["themName"],
就能使用这个themName了。
要改变这个值,就从父组件传递函数就好了。
父组件中
provide(){
return {
themName: this.themName,
changeTheme: this.changeTheme
};
},
data(){
return {
themName: "blue",
fontSize: "normal"
};
},
methods: {
changeTheme(){
if(this.themeName === 'blue'){
this.themeName = 'red'
}else {
this.themeName = 'blue'
}
},
}
子组件中
inject: ["themName", "changeTheme"],
子组件中就可以在methods
中使用
methods: {
x(){
this.changeTheme()
}
}
通过this
来调用,然后通过传递过来的函数,来改变父组件中的data
数据。
总结
provide
和inject
作用:大范围的data
和method
共用
注意:值和改变值的方法都要传递过去。
引用(对象,数组)可以传过去,直接不用方法改父组件的数据,但是感觉不规范,不用传方法就可以改变了,很容易不知道数据在哪被改变。