vue3 provide inject如何把它变成相应式的

184 阅读2分钟

在 Vue 3 中,provideinject 是用于在组件树中共享状态的工具。provide 用于提供数据,inject 用于接收数据。为了使提供的数据是响应式的,我们可以利用 Vue 3 的 reactiveref 来实现。

以下是一个详细的示例,展示如何使用 provideinject 以及如何使数据响应式。

示例代码

父组件 (Provider)

<template>
  <div>
    <h1>Parent Component</h1>
    <button @click="increment">Increment</button>
    <p>Count: {{ state.count }}</p>
    <ChildComponent />
  </div>
</template>

<script>
import { reactive, provide } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default {
  name: 'ParentComponent',
  components: {
    ChildComponent
  },
  setup() {
    const state = reactive({
      count: 0
    });

    const increment = () => {
      state.count++;
    };

    provide('state', state);
    provide('increment', increment);

    return {
      state,
      increment
    };
  }
};
</script>

子组件 (Child)

<template>
  <div>
    <h2>Child Component</h2>
    <button @click="increment">Increment from Child</button>
    <p>Count from Parent: {{ state.count }}</p>
  </div>
</template>

<script>
import { inject } from 'vue';

export default {
  name: 'ChildComponent',
  setup() {
    const state = inject('state');
    const increment = inject('increment');

    return {
      state,
      increment
    };
  }
};
</script>

代码讲解

  1. 父组件 (ParentComponent)

    • 模板部分

      • 包含一个按钮和一个显示计数的段落。
      • 包含子组件 ChildComponent
    • 脚本部分

      • 使用 reactive 创建响应式状态对象 state,其中包含一个 count 属性。
      • 定义一个 increment 函数来增加 count
      • 使用 provide 方法将 stateincrement 函数提供给子组件。
      • setup 函数中返回 stateincrement 以便在模板中使用。
  2. 子组件 (ChildComponent)

    • 模板部分

      • 包含一个按钮和一个显示从父组件传递过来的计数的段落。
    • 脚本部分

      • 使用 inject 方法接收父组件提供的 stateincrement
      • setup 函数中返回 stateincrement 以便在模板中使用。

使数据响应式

在 Vue 3 中,reactiveref 都可以用于创建响应式数据:

  • reactive:用于创建包含多个属性的响应式对象。
  • ref:用于创建包含单个属性的响应式对象。

在上述示例中,我们使用了 reactive 来创建一个包含 count 属性的响应式对象 state。这样,当 count 的值改变时,依赖于 count 的所有组件都会自动更新。

总结

通过使用 provideinject,我们可以在组件树中方便地共享状态。结合 reactiveref,我们可以确保这些状态是响应式的,从而在状态变化时自动更新相关的组件。