Home  >  Article  >  Web Front-end  >  Vue3 global component communication provide/inject source code analysis

Vue3 global component communication provide/inject source code analysis

WBOY
WBOYforward
2023-05-14 17:58:061075browse

1. Foreword

As the name suggests, the grandfather-grandson component has a deeper reference relationship than the communication between parent-child components (also called "generation-separated components"):

C component is introduced into In component B, component B is introduced into component A for rendering. At this time, A is the grandpa level of C (there may be more hierarchical relationships). If you use props, you can only pass them level by level, which is too cumbersome. , so we need a more direct method of communication.

The relationship between them is as follows. Grandson.vue is not directly mounted under Grandfather.vue. There is at least one Son.vue between them (there may be multiple):

Grandfather.vue
└─Son.vue
  └─Grandson.vue

Because of the consistency of the relationship between superiors and subordinates, the scheme of grandfather-grandson component communication is also applicable to parent-child component communication. You only need to replace the grandfather-grandson relationship with a father-son relationship.

2. provide / inject

This feature has two parts: Grandfather.vue has a provide option to provide data, and Grandson.vue has an inject option to start using the data. .

  • Grandfather.vue passes value to Grandson.vue through provide (can include defined functions)

  • Grandson.vue passes value to Grandfather through inject .vue triggers the event execution of the grandpa component

No matter how deep the component hierarchy is, the component that initiates provide can be used as a dependency provider for all its subordinate components
The content of this part The changes are very big, but it is actually very simple to use. Don't panic, there are also the same places:

  • The parent component does not need to know which child components use the property it provides

  • Subcomponents do not need to know where the inject property comes from

In addition, one thing to remember is that the provide and inject bindings are not responsive. This is intentional, but if a listenable object is passed in, the object's properties will still be responsive.

3. Initiate provide

Let’s first review the usage of 2.x:

export default {
  // 定义好数据
  data () {
    return {
      tags: [ '中餐', '粤菜', '烧腊' ]
    }
  },
  // provide出去
  provide () {
    return {
      tags: this.tags
    }
  }
}

The old version of provide usage is similar to data, both are configured as a return object function.
3.x’s new version of provide is quite different in usage from 2.x.

In 3.x, provide needs to be imported and enabled in setup, and is now a completely new method.
Every time you want to provide a piece of data, you must call it separately.
Every time you call, you need to pass in 2 parameters:

##valueanyValue of data
Parameters Type Description
key string The name of the data
Let’s take a look at how to create a provide:

// 记得导入provide
import { defineComponent, provide } from 'vue'

export default defineComponent({
  // ...
  setup () {
    // 定义好数据
    const msg: string = 'Hello World!';

    // provide出去
    provide('msg', msg);
  }
})

The operation is very simple, right, but it should be noted that provide is not a response style, if you want to make it responsive, you need to pass in responsive data

4, receive inject

Let’s first review the usage of 2.x:

export default {
  inject: ['tags'],
  mounted () {
    console.log(this.tags);
  }
}

The usage of the old version of inject is similar to that of props. The usage of the new version of 3.x inject is also quite different from that of 2.x.

In 3.x, inject is the same as provide. It also needs to be imported first and then enabled in setup. It is also a brand new method.

Every time you want to inject a piece of data, you must call it separately.
Every time you call, you only need to pass in 1 parameter:

ParameterTypeDescriptionkeystringThe data name corresponding to provide
// 记得导入inject
import { defineComponent, inject } from 'vue'

export default defineComponent({
  // ...
  setup () {
    const msg: string = inject('msg') || '';
  }
})

也是很简单(写 TS 的话,由于 inject 到的值可能是 undefined,所以要么加个 undefined 类型,要么给变量设置一个空的默认值)。

5、响应性数据的传递与接收

之所以要单独拿出来说, 是因为变化真的很大

在前面我们已经知道,provide 和 inject 本身不可响应,但是并非完全不能够拿到响应的结果,只需要我们传入的数据具备响应性,它依然能够提供响应支持。

我们以 ref 和 reactive 为例,来看看应该怎么发起 provide 和接收 inject。

先在 Grandfather.vue 里 provide 数据:

export default defineComponent({
  // ...
  setup () {
    // provide一个ref
    const msg = ref<string>(&#39;Hello World!&#39;);
    provide(&#39;msg&#39;, msg);

    // provide一个reactive
    const userInfo: Member = reactive({
      id: 1,
      name: &#39;Petter&#39;
    });
    provide(&#39;userInfo&#39;, userInfo);

    // 2s 后更新数据
    setTimeout(() => {
      // 修改消息内容
      msg.value = &#39;Hi World!&#39;;

      // 修改用户名
      userInfo.name = &#39;Tom&#39;;
    }, 2000);
  }
})

在 Grandsun.vue 里 inject 拿到数据:

export default defineComponent({
  setup () {
    // 获取数据
    const msg = inject(&#39;msg&#39;);
    const userInfo = inject(&#39;userInfo&#39;);

    // 打印刚刚拿到的数据
    console.log(msg);
    console.log(userInfo);

    // 因为 2s 后数据会变,我们 3s 后再看下,可以争取拿到新的数据
    setTimeout(() => {
      console.log(msg);
      console.log(userInfo);
    }, 3000);

    // 响应式数据还可以直接给 template 使用,会实时更新
    return {
      msg,
      userInfo
    }
  }
})

非常简单,非常方便!!!

响应式的数据 provide 出去,在子孙组件拿到的也是响应式的,并且可以如同自身定义的响应式变量一样,直接 return 给 template 使用,一旦数据有变化,视图也会立即更新。

但上面这句话有效的前提是,不破坏数据的响应性,比如 ref 变量,你需要完整的传入,而不能只传入它的 value,对于 reactive 也是同理,不能直接解构去破坏原本的响应性

切记!切记!!!

6、引用类型的传递与接收 (针对非响应性数据的处理)

provide 和 inject 并不是可响应的,这是官方的故意设计,但是由于引用类型的特殊性,在子孙组件拿到了数据之后,他们的属性还是可以正常的响应变化。

先在 Grandfather.vue 里 provide 数据:

export default defineComponent({
  // ...
  setup () {
    // provide 一个数组
    const tags: string[] = [ &#39;中餐&#39;, &#39;粤菜&#39;, &#39;烧腊&#39; ];
    provide(&#39;tags&#39;, tags);

    // provide 一个对象
    const userInfo: Member = {
      id: 1,
      name: &#39;Petter&#39;
    };
    provide(&#39;userInfo&#39;, userInfo);

    // 2s 后更新数据
    setTimeout(() => {
      // 增加tags的长度
      tags.push(&#39;叉烧&#39;);

      // 修改userInfo的属性值
      userInfo.name = &#39;Tom&#39;;
    }, 2000);
  }
})

在 Grandsun.vue 里 inject 拿到数据:

export default defineComponent({
  setup () {
    // 获取数据
    const tags: string[] = inject(&#39;tags&#39;) || [];
    const userInfo: Member = inject(&#39;userInfo&#39;) || {
      id: 0,
      name: &#39;&#39;
    };

    // 打印刚刚拿到的数据
    console.log(tags);
    console.log(tags.length);
    console.log(userInfo);

    // 因为 2s 后数据会变,我们 3s 后再看下,能够看到已经是更新后的数据了
    setTimeout(() => {
      console.log(tags);
      console.log(tags.length);
      console.log(userInfo);
    }, 3000);
  }
})

export default defineComponent({
  setup () {
    // 获取数据
    const tags: string[] = inject(&#39;tags&#39;) || [];
    const userInfo: Member = inject(&#39;userInfo&#39;) || {
      id: 0,
      name: &#39;&#39;
    };

    // 打印刚刚拿到的数据
    console.log(tags);
    console.log(tags.length);
    console.log(userInfo);

    // 因为 2s 后数据会变,我们 3s 后再看下,能够看到已经是更新后的数据了
    setTimeout(() => {
      console.log(tags);
      console.log(tags.length);
      console.log(userInfo);
    }, 3000);
  }
})

引用类型的数据,拿到后可以直接用,属性的值更新后,子孙组件也会被更新。
但是!!!由于不具备真正的响应性,return 给模板使用依然不会更新视图,如果涉及到视图的数据,请依然使用 响应式 API 。

7、基本类型的传递与接收 (针对非响应性数据的处理)

基本数据类型被直接 provide 出去后,再怎么修改,都无法更新下去,子孙组件拿到的永远是第一次的那个值。

先在 Grandfather.vue 里 provide 数据:

export default defineComponent({
  // ...
  setup () {
    // provide 一个数组的长度
    const tags: string[] = [ &#39;中餐&#39;, &#39;粤菜&#39;, &#39;烧腊&#39; ];
    provide(&#39;tagsCount&#39;, tags.length);

    // provide 一个字符串
    let name: string = &#39;Petter&#39;;
    provide(&#39;name&#39;, name);

    // 2s 后更新数据
    setTimeout(() => {
      // tagsCount 在 Grandson 那边依然是 3
      tags.push(&#39;叉烧&#39;);

      // name 在 Grandson 那边依然是 Petter
      name = &#39;Tom&#39;;
    }, 2000);
  }
})

在 Grandsun.vue 里 inject 拿到数据:

export default defineComponent({
  setup () {
    // 获取数据
    const name: string = inject(&#39;name&#39;) || &#39;&#39;;
    const tagsCount: number = inject(&#39;tagsCount&#39;) || 0;

    // 打印刚刚拿到的数据
    console.log(name);
    console.log(tagsCount);

    // 因为 2s 后数据会变,我们 3s 后再看下
    setTimeout(() => {
      // 依然是 Petter
      console.log(name);

      // 依然是 3
      console.log(tagsCount);
    }, 3000);
  }
})

很失望,并没有变化。


那么是否一定要定义成响应式数据或者引用类型数据呢?

当然不是,我们在 provide 的时候,也可以稍作修改,让它能够同步更新下去。

先在 Grandfather.vue 里 provide 数据:

export default defineComponent({
  // ...
  setup () {
    // provide 一个数组的长度
    const tags: string[] = [ &#39;中餐&#39;, &#39;粤菜&#39;, &#39;烧腊&#39; ];
    provide(&#39;tagsCount&#39;, (): number => {
      return tags.length;
    });

    // provide 字符串
    let name: string = &#39;Petter&#39;;
    provide(&#39;name&#39;, (): string => {
      return name;
    });

    // 2s 后更新数据
    setTimeout(() => {
      // tagsCount 现在可以正常拿到 4 了
      tags.push(&#39;叉烧&#39;);

      // name 现在可以正常拿到 Tom 了
      name = &#39;Tom&#39;;
    }, 2000);
  }
})

再来 Grandsun.vue 里修改一下 inject 的方式,看看这次拿到的数据:

export default defineComponent({
  setup () {
    // 获取数据
    const tagsCount: any = inject(&#39;tagsCount&#39;);
    const name: any = inject(&#39;name&#39;);

    // 打印刚刚拿到的数据
    console.log(tagsCount());
    console.log(name());

    // 因为 2s 后数据会变,我们 3s 后再看下
    setTimeout(() => {
      // 现在可以正确得到 4
      console.log(tagsCount());

      // 现在可以正确得到 Tom
      console.log(name());
    }, 3000);
  }
})

这次可以正确拿到数据了,看出这2次的写法有什么区别了吗?

基本数据类型,需要 provide 一个函数,将其 return 出去给子孙组件用,这样子孙组件每次拿到的数据才会是新的。
但由于不具备响应性,所以子孙组件每次都需要重新通过执行 inject 得到的函数才能拿到最新的数据。

按我个人习惯来说,使用起来挺别扭的,能不用就不用……

由于不具备真正的响应性,return 给模板使用依然不会更新视图,如果涉及到视图的数据,请依然使用 响应式 API 。

The above is the detailed content of Vue3 global component communication provide/inject source code analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete