Vue入门--第五天--provide/inject

本文介绍了Vue的provide/inject特性,用于子组件改变父组件数据。父组件通过provide提供变量,子组件通过inject接收并使用,若需改变值,建议通过父组件传递的函数进行操作,以保持数据流动的清晰性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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数据。

总结

provideinject
作用:大范围的datamethod共用
注意:和改变值的方法都要传递过去。

引用(对象,数组)可以传过去,直接不用方法改父组件的数据,但是感觉不规范,不用传方法就可以改变了,很容易不知道数据在哪被改变。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值