a组件和e,f,i 组件通讯vue
a组件ide
//a组件 <template> <div> <button @click="changeColor" :style="{color:color}">a页面</button> <a-b></a-b> </div> </template> <script> import aB from './ab.vue' export default {
// 这种写法 provide 非响应式,由于 return 的是theme 而 this.color 发生变化不会 触发return // provide(){ // return { // theme:{ // color:this.color // } // } // }, provide(){ return { theme:this } }, data() { return { color:'red' } }, components:{ aB }, methods: { changeColor(color){ if(typeof(color)=="string"){ this.color = color; }else{ this.color = this.color ==='red'? "blue":"red"; } } }, } </script>
<template> <div> <div :style="{color:theme1.color}">e组件</div> <button @click="handleClick">改变颜色为green</button> </div> </template> <script> export default { inject: { theme1: { from:'theme',//这里定义了theme1 是来自 theme 的 若是这个组件自己已经有一个theme 能够用from 重命名一个 default: () => ({}) } }, methods: { handleClick() { console.log(this); if (this.theme1.changeColor) { this.theme1.changeColor("green"); } } } }; </script>