Table of Contents
1. Foreword
2. provide / inject
3. Initiate provide
5、响应性数据的传递与接收
6、引用类型的传递与接收 (针对非响应性数据的处理)
7、基本类型的传递与接收 (针对非响应性数据的处理)
Home Web Front-end Vue.js Vue3 global component communication provide/inject source code analysis

Vue3 global component communication provide/inject source code analysis

May 14, 2023 pm 05:58 PM
vue3 provide inject

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
Copy after login

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
    }
  }
}
Copy after login

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
ParametersTypeDescription
keystringThe 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);
  }
})
Copy after login

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);
  }
}
Copy after login

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') || '';
  }
})
Copy after login

也是很简单(写 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);
  }
})
Copy after login

在 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
    }
  }
})
Copy after login

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

响应式的数据 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);
  }
})
Copy after login

在 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);
  }
})
Copy after login

引用类型的数据,拿到后可以直接用,属性的值更新后,子孙组件也会被更新。
但是!!!由于不具备真正的响应性,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);
  }
})
Copy after login

在 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);
  }
})
Copy after login

很失望,并没有变化。


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

当然不是,我们在 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);
  }
})
Copy after login

再来 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);
  }
})
Copy after login

这次可以正确拿到数据了,看出这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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

vue3+vite: How to solve the error when using require to dynamically import images in src vue3+vite: How to solve the error when using require to dynamically import images in src May 21, 2023 pm 03:16 PM

vue3+vite:src uses require to dynamically import images and error reports and solutions. vue3+vite dynamically imports multiple images. If vue3 is using typescript development, require will introduce image errors. requireisnotdefined cannot be used like vue2 such as imgUrl:require(' .../assets/test.png') is imported because typescript does not support require, so import is used. Here is how to solve it: use awaitimport

How to use tinymce in vue3 project How to use tinymce in vue3 project May 19, 2023 pm 08:40 PM

tinymce is a fully functional rich text editor plug-in, but introducing tinymce into vue is not as smooth as other Vue rich text plug-ins. tinymce itself is not suitable for Vue, and @tinymce/tinymce-vue needs to be introduced, and It is a foreign rich text plug-in and has not passed the Chinese version. You need to download the translation package from its official website (you may need to bypass the firewall). 1. Install related dependencies npminstalltinymce-Snpminstall@tinymce/tinymce-vue-S2. Download the Chinese package 3. Introduce the skin and Chinese package. Create a new tinymce folder in the project public folder and download the

How Vue3 parses markdown and implements code highlighting How Vue3 parses markdown and implements code highlighting May 20, 2023 pm 04:16 PM

Vue implements the blog front-end and needs to implement markdown parsing. If there is code, it needs to implement code highlighting. There are many markdown parsing libraries for Vue, such as markdown-it, vue-markdown-loader, marked, vue-markdown, etc. These libraries are all very similar. Marked is used here, and highlight.js is used as the code highlighting library. The specific implementation steps are as follows: 1. Install dependent libraries. Open the command window under the vue project and enter the following command npminstallmarked-save//marked to convert markdown into htmlnpmins

How to refresh partial content of the page in Vue3 How to refresh partial content of the page in Vue3 May 26, 2023 pm 05:31 PM

To achieve partial refresh of the page, we only need to implement the re-rendering of the local component (dom). In Vue, the easiest way to achieve this effect is to use the v-if directive. In Vue2, in addition to using the v-if instruction to re-render the local dom, we can also create a new blank component. When we need to refresh the local page, jump to this blank component page, and then jump back in the beforeRouteEnter guard in the blank component. original page. As shown in the figure below, how to click the refresh button in Vue3.X to reload the DOM within the red box and display the corresponding loading status. Since the guard in the component in the scriptsetup syntax in Vue3.X only has o

How to select an avatar and crop it in Vue3 How to select an avatar and crop it in Vue3 May 29, 2023 am 10:22 AM

The final effect is to install the VueCropper component yarnaddvue-cropper@next. The above installation value is for Vue3. If it is Vue2 or you want to use other methods to reference, please visit its official npm address: official tutorial. It is also very simple to reference and use it in a component. You only need to introduce the corresponding component and its style file. I do not reference it globally here, but only introduce import{userInfoByRequest}from'../js/api' in my component file. import{VueCropper}from'vue-cropper&

How to use Vue3 reusable components How to use Vue3 reusable components May 20, 2023 pm 07:25 PM

Preface Whether it is vue or react, when we encounter multiple repeated codes, we will think about how to reuse these codes instead of filling a file with a bunch of redundant codes. In fact, both vue and react can achieve reuse by extracting components, but if you encounter some small code fragments and you don’t want to extract another file, in comparison, react can be used in the same Declare the corresponding widget in the file, or implement it through renderfunction, such as: constDemo:FC=({msg})=>{returndemomsgis{msg}}constApp:FC=()=>{return(

How to use defineCustomElement to define components in Vue3 How to use defineCustomElement to define components in Vue3 May 28, 2023 am 11:29 AM

Using Vue to build custom elements WebComponents is a collective name for a set of web native APIs that allow developers to create reusable custom elements (customelements). The main benefit of custom elements is that they can be used with any framework, even without one. They are ideal when you are targeting end users who may be using a different front-end technology stack, or when you want to decouple the final application from the implementation details of the components it uses. Vue and WebComponents are complementary technologies, and Vue provides excellent support for using and creating custom elements. You can integrate custom elements into existing Vue applications, or use Vue to build

How to use vue3+ts+axios+pinia to achieve senseless refresh How to use vue3+ts+axios+pinia to achieve senseless refresh May 25, 2023 pm 03:37 PM

vue3+ts+axios+pinia realizes senseless refresh 1. First download aiXos and pinianpmipinia in the project--savenpminstallaxios--save2. Encapsulate axios request-----Download js-cookienpmiJS-cookie-s//Introduce aixosimporttype{AxiosRequestConfig ,AxiosResponse}from"axios";importaxiosfrom'axios';import{ElMess

See all articles