Vue高阶用法:provide / inject


今天写项目的时候,需要把父组件的值传给子和孙子,传统的props只能父传子,看了一下vuejs的官方文档,有个provide / inject。

这对选项需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在其上下游关系成立的时间里始终生效。如果你熟悉 React,这与 React 的上下文特性很相似。

提示:provide 和 inject 绑定并不是可响应的。这是刻意为之的。然而,如果你传入了一个可监听的对象,那么其对象的 property 还是可响应的。

例子代码如下:

父组件




子组件




孙子组件




注意:要传递对象,否则无法改变值

实际项目中运用的代码如下

父组件





export default {
  components: {
    GatewayTableCard,
    AppListCard,
    AppRelationCard,
    MonitoringCenterCard,
  },
  //依赖注入传值
  provide() {
    return {
      newFoo: this.edgexGatewatDate
    }
  },
  data() {
    return {
      edgexGatewatDate: {
        deviceState: 0
      },
    }
  },
  methods: {
      handleGatewayTableRowClick(item) {
        this.edgexGatewatDate.deviceState = item.deviceState // 未启用时应用状态等禁用
        // console.log('this.edgexGatewatDate', this.edgexGatewatDate)
        if (this.selectedGatewayId === item.id) {
          return;
        }
        this.selectedGatewayId = item.id;
        this.$refs.appListCard.apiGetEdgeGatewayAppList(item.id);
        this.$refs.appRelationCard.apiGetEdgeGatewayRelate(item.id);
        this.$refs.monitoringCenterCard.apiGetDeviceProViewList(item.id);
    },
  }
}

子组件