Vue2之使用provide与inject调用方法案例

在Vue 2中,provideinject是用于在组件之间传递数据的一种高级技术。虽然它们通常用于传递数据,但也可以用于传递方法。

1. 祖先组件使用provide提供方法

Parent.vue中通过provide提供方法

// Parent.vue
export default {
  data() {
    return {
      message: 'hello,父组件中的方法被执行了',
    };
  },
  methods: {
    sayHello() {
      console.log(this.message);
    },
  },
  //注意:提供方式时provide是一个函数,且将调用的方法写在return对象中,而提供方法时provide是一对象
  provide() {
    return {
      callParentMethod: this.sayHello // 提供方法,注意提供的方法要写在return对象中
    };
  },
};

2. 后代组件使用inject注入并调用方法

在后代组件Child.vue中使用inject来获取父组件提供的方法

export default {
  inject: ['callParentMethod'], // 注入方法
  mounted() {
    this.callParentMethod(); // 调用注入的方法
  },
};
Logo

一站式 AI 云服务平台

更多推荐