这对选项需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在其上下游关系成立的时间里始终生效。 ——vue 官方
这里的案例拿vue-element-admin的源码来说明:
该项目架构中,App.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(function() {
this.isRouterAlive = true
})
}
}
}
</script>
在基础的业务场景中,修改数据,重新请求的方式可以换成如下:
// index.vue 子组件注入
<template>
<div class="index">
</div>
</template>
<script>
export default {
inject: ['reload'], // 注入方法
method: {
updateInfo() {
// ...接口请求成功
this.reload() // 调用此方法 刷新作用
}
}
}
</script>
这种方法可能会跟其他的混入(mixin), 扩展(extends)混淆。可以看下我上一篇文章Vue高级接口extend,extends,mixin使用与对比
若对你有所帮助,请不吝点赞,共同进步~~~