Usage and principles of provide and inject in Vue3

Usage and principles of provide and inject in Vue3

Preface:

When passing data between parent and child components, props and emit are usually used. When passing data from parent to child, props is used. If the parent component passes it to the grandchild component, it needs to be passed to the child component first, and then the child component passes it to the grandchild component. If multiple child components or multiple grandchild components are used, it needs to be passed many times, which will be very troublesome.

In cases like this, you can use provide and inject to solve this problem. No matter how deeply the components are nested, the parent component can provide data for all child components or grandchild components. The parent component uses provide to provide data, and the child or grandchild components inject to inject data. At the same time, it is more convenient to transfer values ​​between brother components.

1. Use of provide / inject in Vue2

provide: is an object containing properties and values. like:

provide:{

 info:"value"

}

If provide needs to use the data in data , writing it like this will result in an error. When accessing a component instance property , you need to convert provide into a function that returns an object.

provide(){

 return {

  info: this.msg

 }

}

inject : is an array of strings. like:

inject: [ 'info' ]

Receives the info data provided by provide above, which can also be an object containing from and default attributes. From is the key used to search in the injected content, and the default attribute is to specify the default value.

In vue2 project/inject application:

//Parent component export default{

 provide:{

  info:"Provide data"

 }

}

//Subcomponent export default{

 inject:['info'],

 mounted(){

     console.log("Receive data:", this.info) // Receive data: Provide data}

}

provide / inject is similar to subscribing and publishing messages. provide provides or sends data, inject receives data.

2. Use of provide / inject in Vue3

Use provide/inject in the combined API . Both can only be called during setup . Before using, you must explicitly import provide/inject method from vue .

The provide function receives two parameters:

provide( name,value )

  • name : defines name of the provided property .
  • value : the value of property .

When using:

import { provide } from "vue"

export default {

  setup(){

    provide('info',"value")

  }

}

The inject function takes two parameters:

inject(name,default)

  • name : Receives the attribute name provided by provide .
  • default : Set the default value. It is optional.

When using:

import { inject } from "vue"

export default {

  setup(){

    inject('info',"Set default value")

  }

}

Complete example 1 : provide/inject example

//Parent component code <script>

import { provide } from "vue"

export default {

  setup(){

    provide('info',"value")

  }

}

</script>

//Subcomponent code <template>

 {{info}}

</template>

<script>

import { inject } from "vue"

export default {

  setup(){

    const info = inject('info')

    return {

      info

    }

  }

}

</script>

3. Add responsiveness

To add responsiveness to provide/inject , use ref or reactive .

Complete Example 2 : provide/inject Responsive

//Parent component code <template>

  <div>

    info:{{info}}

    <InjectCom ></InjectCom>

  </div>

</template>

<script>

import InjectCom from "./InjectCom"

import { provide,readonly,ref } from "vue"

export default {

  setup(){

    let info = ref("Have you studied today?")

    setTimeout(()=>{

      info.value = "Don't make excuses, start learning now"

    },2000)

    provide('info',info)

    return {

      info

    }

  },

  components:{

    InjectCom

  }

}

</script>

// InjectCom subcomponent code <template>

 {{info}}

</template>

<script>

import { inject } from "vue"

export default {

  setup(){

    const info = inject('info')

    setTimeout(()=>{

      info.value = "Update"

    },2000)

    return {

      info

    }

  }

}

</script>

In the above example, the value of info will be modified in both the parent component and the child component.

provide / inject is similar to message subscription and publishing, following the unidirectional data flow in vue . What does it mean? That is, the data can only be modified where it is. Data cannot be modified at the point where it is transmitted, which can easily cause unpredictable status.

When modifying the value in the subscription component, it can be modified normally. If other components also use the value, the status is likely to be confused, so it is necessary to avoid the problem at the source.

readonly is a read-only function that needs to be introduced before use. If the readonly attribute is added to a variable, the data can only be read but cannot be changed. A warning will be issued when it is modified, but the value will not be changed.

Directions:

import { readonly } from "vue"

let info = readonly('read-only info value')

setTimout(()=>{

 info="Update info" //Update the value of info after two seconds},2000)

After running for two seconds, the browser issues a warning, indicating that the info value cannot be modified.

So we add a read-only attribute to the data emitted by provide to prevent the emitted data from being modified.

Add readonly to provide in the complete example 2.

provide('info', readonly(info))

When a subcomponent modifies the value, there will be a read-only reminder.

When modifying the value, you still need to modify the data in the component that provide the published data, so a modification method will be added to the component and published at the same time, and can be called in the child component.

like:

//Publish let info = ref("Have you studied today?")

const changeInfo = (val)=>{

 info.value = val

}

provide('info',readonly(info))

provide('changeInfo',changeInfo)



//Subscription const chang = inject('changeInfo')

chang('rush to front-end engineer')

Complete Example 3: Modifying Data

// Parent component code <template>

  <div>

    info:{{info}}

    <InjectCom ></InjectCom>

  </div>

</template>



<script>

import InjectCom from "./InjectCom"

import { provide,readonly,ref } from "vue"

export default {

  setup(){

    let info = ref("Have you studied today?")

    const changeInfo = (val)=>{

      info.value = val

    }

    provide('info',readonly(info))

    provide('changeInfo',changeInfo)

    return {

      info

    }

  },

  components:{

    InjectCom

  }

}

</script>



//InjectCom subcomponent code <template>

  <div>

    <button @click="chang('Rush to the front-end engineer')">Update value</button>

  </div>

</template>

<script>

import { inject } from "vue"

export default {

  setup(){

    const info = inject('info')

    const chang = inject('changeInfo')

    return {

      info,

      Chang

    }

  }

}

</script>
 

This is the end of this article about the usage and principles of provide and inject in vue3 . For more relevant content about provide and inject in vue3, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Sharing the implementation principle of Provide/Inject in Vue3
  • Use of provide and inject in Vue3
  • Sharing tips on using Vue3 provide and inject

<<:  CSS Viewport Units for Fast Layout

>>:  How to create a stylish web page design (graphic tutorial)

Recommend

Perfect solution to MySQL common insufficient memory startup failure

1. If MySQL is not started successfully, check th...

Add ico mirror code to html (favicon.ico is placed in the root directory)

Code: Copy code The code is as follows: <!DOCTY...

Implementation of MySQL Shell import_table data import

Table of contents 1. Introduction to import_table...

Two ways to build Docker images

Table of contents Update the image from an existi...

CSS3 uses the transition property to achieve transition effects

Detailed description of properties The purpose of...

Complete steps for vue dynamic binding icons

0 Differences between icons and images Icons are ...

JavaScript web page entry-level development detailed explanation

Part 3: ❤Three ways to overlook backend data rece...

Vue handwriting loading animation project

When the page is not responding, displaying the l...

How to introduce img images into Vue pages

When we learn HTML, the image tag <img> int...

Detailed explanation of redundant and duplicate indexes in MySQL

MySQL allows you to create multiple indexes on th...

How to enable MySQL remote connection in Linux server

Preface Learn MySQL to reorganize previous non-MK...