Hello大家周末好,今天给大家讲一下inject(注入)
在每个 new Vue 实例的子组件中,其根实例可以通过 r o o t 属 性 进 行 访 问 , root 属性进行访问,root属性进行访问,r o o t 直 接 找 的 是 根 父 亲 , 调 用 方 法 和 root直接找的是根父亲,调用方法和root直接找的是根父亲,调用方法和r e f s 的 方 式 很 像 , t h i s . refs的方式很像,this.refs的方式很像,this.root.xxxx,但是很多项目需求不能直接用这个root和refs来调用组件嵌套太多了,很难定位到某一层的组件然后主角inject上场,先看下项目目录结构
inject/index.vue是入口文件(就是最大的父亲),injectChildren文件下有a,b,c组件,这三个组件项目嵌套 a 引入 b , b 引入 c ,index.vue 引入a
我以前是用this.$parent.来往上找的这样后期维护或者添加新的需求维护性太差了,改变一个结构可能会改好多地方,这时候我们用vue官方推荐的inject来引入需要调用的方法,在Index.vue中把别处子组件需要的东西抛出
<template>
<div>
<A></A>
</div>
</template>
<script>
import A from "./injectChildren/a.vue";
export default {
data() {
return {};
},
components: { A },
**************************
provide: function() {
return {
hello: this.hello //这里this.hello就是下面的这个函数,是需要以key,value的方式导出这个方法,然后在需要用的子组件中引入
};
},
************************
methods: {
hello() {
console.log("我是注入的方法");
}
}
};
</script>
c组件需要用,在c引用
<template>
<div>
<button @click="word">我是c组件</button>
</div>
</template>
<script>
export default {
inject: ["hello"], //inject注入这里的hello是咱们在前面定义的key,前面定义的是什么这里就引入的是什么
methods: {
word() {
// this.$parent.$parent.$parent.hello();
this.hello();
}
}
};
</script>
输出结果
这样便于以后的维护和迭代开发,不需要我们一层一层的找使用很多的parent.parent的看上去都感觉很low哈哈 。
今天就到这里,谢谢大家。