vue项目中inject使用
1. 使用场景:由于vue有$parent属性可以让子组件访问父组件。但孙组件想要访问祖先组件就比较困难。通过provide/inject可以轻松实现跨级访问祖先组件的数据。
一种最常见的用法是刷新vue组件
//app.vue
<template>
<div id="app">
<router-view v-if="isRouterAlive"/>
</div>
</template>
<script>
export default{
name:'App',
//父组件中返回要传给下级的数据
provide() {
return {
reload: this.reload,
}
},
data(){
return{
isRouterAlive:true
}
},
methods:{
reload(){
this.isRouterAlive=false
this.$nextTick(()=>{
this.isRouterAlive=true
})
}
}
}
</script>
<template></template>
<script>
export default{
//引用vue reload 方法
inject:['reload'],
methods:{
this.reload()
}
}
</script>
这样就实现了子组件调取reload方法实现刷新vue组件的功能,实现了组件跨越组件传递数据方法。
第二种是祖孙元素调取
//ancestor.vue
<template>
<div id="app"></div>
</template>
<script>
export default{
data(){
return{
datas: [
{
id: 1,
label: '产品一'
},
{
id: 1,
label: '产品二'
},
{
id: 1,
label: '产品三'
}
]
}
},
provide{
return {
dattas:this.datas
}
}
}
</script>
//后代组件
<template>
<div>
<ul>
<li v-for="(item,index) in datas" :key="index">{{item.label}}</li>
</ul>
</div>
</template>
<script>
export default{
inject:['datas']
}
</script>
//后代元素引入被注入数据datas,并在组件内循坏输出
在父组件里面
provide() {
return {
Index: this,
};
},
methods:{
openMenu() {
//进行某些操作
},
}
在子级组件调用openMenu方法
inject: ["Index"],
created(){
this.Index.openMenu();
}