vue 跨組件通訊(provide、inject)

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>
相關文章
相關標籤/搜索