当前位置:网站首页>Analysis on the usage, response and global delivery of provide/inject

Analysis on the usage, response and global delivery of provide/inject

2022-06-13 04:42:00 Dax1_

Preface

Vue Value passed between parent and child of : props

Values are passed between components that are nested more deeply : provide/inject

More complex structure :vuex

provide/inject

Provide / Inject

provide

  • An object or a function that returns an object . This object contains properties that can be injected into its descendants . You can use... In this object ES2015 Symbols As key, But only in native support Symbol and Reflect.ownKeys Working in an environment of .

inject

  • An array of strings , Or an object

Use scenarios

 Insert picture description here

For example, such a hierarchy

Root
└─  Components A
   ├─  Components B
   └─  Components C
      ├─  Components D
      └─  Components E

If you want to Components A The data is passed directly to Components E, We're going to prop Pass it on step by step : Components A -> Components C -> Components E. And by provide/inject , Directly from Components A Pass to Components E

Usage method

//  Parent component / Ancestor component  , Provide provide
// The first one is 
export default {
    
  name: "grandfather",
  provide(){
    
    return{
    
      foo:'halo'
    }
  },
}

// The second kind 
export default {
    
  name: "grandfather",
  provide:{
    
    foo:'halo~~~~'
  },
}
//  Descendant components  , Inject inject
export default {
    
  inject:['foo'],
}

provide Method

Of the ancestor component provide Only the first method is recommended , That is, function writing . If the data you want to pass is just a string , There is no difference between the two methods , But the second way ( Object writing ) Cannot pass object .

provide/inject Not responsive

Official documents

provide  and  inject  Binding is not responsive . This is intentional . However , If you pass in a listener object , Then the properties of its objects are still responsive .

We can pass an object , To achieve data responsive .

//  Ancestor component 
data() {
    
  return {
    
    obj:{
    name:'dax1'},
  }
}
provide(){
    
  return{
    
    username:this.obj	//  here provide An object 
  }
},
//  Descendant components 
export default {
    
    inject: ['username']    
}

here username It's responsive data , because The properties of an object are responsive .

Achieve global delivery

provide/inject It can only be passed from ancestor to offspring , But it can be done by App.vue binding provide, All subcomponents can be injected inject, So as to achieve global transmission .


Reference documents

Provide / Inject | Vue.js (vuejs.org)

You may not know provide/inject usage

原网站

版权声明
本文为[Dax1_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280521342976.html