vue 跨组件通信(provide、inject)

a组件和e,f,i 组件通信

a组件

//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>
原文地址:https://www.cnblogs.com/caoruichun/p/10763835.html