// this.theme.color = this.theme.color === "blue" ? "red" : "blue";
// }
// }
// }
// F 组件
<template functional>
<div class="border2">
<h3 :style="{ color: injections.theme.color }">F 组件</h3>
</div>
</template>
<script>
export default {
inject: {
theme: {
//函数式组件取值不一样
default: () => ({})
}
}
};
</script>
虽说provide 和 inject 主要为高阶插件/组件库提供用例,但假设你能在业务中熟练运用,可以到达事半功倍的效果!
办法六、$parent / $children与 ref
ref:假设在普通的 DOM 元素上运用,援用指向的就是 DOM 元素;假设用在子组件上,援用就指向组件实例
$parent / $children:拜访父 / 子实例
需求留意的是:这两种都是直接失掉组件实例,运用后可以直接调用组件的办法或拜访数据。我们先来看个用 ref来拜访组件的例子:
// component-a 子组件
export default {
data () {
return {
title: 'Vue.js'
}
},
methods: {
sayHello () {
window.alert('Hello');
}
}
}
// 父组件
<template>
<component-a ref="comA"></component-a>
</template>
<script>
export default {
mounted () {
const comA = this.$refs.comA;
console.log(comA.title); // Vue.js
comA.sayHello(); // 弹窗
}
}
</script>
不过,这两种办法的弊端是,无法在跨级或兄弟间通讯。
// parent.vue
<component-a></component-a>
<component-b></component-b>
<component-b></component-b>
我们想在 component-a 中,拜访到援用它的页面中(这里就是 parent.vue)的两个 component-b 组件,那这种状况下,就得配置额外的插件或工具了,比如 Vuex 和 Bus 的处置方案。
总结
常见运用场景可以分为三类:
父子通讯:
父向子传递数据是经过 props,子向父是经过 events($emit);经过父链 / 子链也可以通讯($parent / $children);ref 也可以拜访组件实例;provide / inject API;$attrs/$listeners
兄弟通讯:
Bus;Vuex
跨级通讯:
Bus;Vuex;provide / inject API、$attrs/$listeners
【编辑引荐】
8种vue组件通讯方式详细解析实例
我为什么选择 Vue 而不是 React?
一个Java顺序猿眼中的前后端别离以及Vue.js入门
用vscode开发vue运用
Linux下的进程间通讯:共享存储
(责任编辑:admin)