一文搞定Vue2組件通訊

vue 組件通訊方式

  1. 父組件將自己的狀態分享給子組件使用;

    方法:父組件通過子標籤傳遞數據,子組件通過 props 接收

  2. 子組件改變父組件的狀態;

    方法:父組件在子標籤上通過@abc 提供一個改變自身狀態的方法,子組件通過$emit(“abc”, payload)觸發這個函數

  3. 父組件直接改變子組件的狀態;

    方法:父組件設法($ref,$children[0])拿到子組件實例對象,然後通過實例對象直接修改子組件狀態

  4. 子組件直接改變父組件的狀態

    方法:子組件通過$parent拿到父組件的改變自身狀態的方法,然後直接調用($parent 可以拿到父組件狀態,但是最好不要直接修改,而是通過父組件函數式修改,保持單向數據流)

  5. 父組件通過插槽向子組件傳遞數據

    方法:子組件定義具名插槽,父組件向插槽內傳遞自己的狀態

  6. 父組件向後代組件傳值

    方法:父組件正常在標籤上向子組件傳遞數據,子組件不用 props 接收屬性,通過$attrs獲取屬性,通過$listeners 獲取方法。子組件再向下傳遞時,使用 v-bind=”$attr”傳遞屬性,使用v-on=”$listeners”傳遞方法

  7. 父組件向後代組件傳值

    方法:父組件js中定義provide函數提供數據源,後代組件通過inject去接收,inject可以是一個數組或對象。

    注意:父組件提供的數據源如果不是響應式的,那麼後代修改數據,數據不會響應變化。如果父組件提供的數據源是響應式的,但是不是一個對象,那麼它也不是響應式的,所以要用對象在外包一層對象(數組不行)。另外,如果子組件同時provide一個inject祖先組件相同名稱的數據,那麼子組件的後代會就近使用子組件的數據。

    官網tip:provide 和 inject 綁定並不是可響應的。這是刻意為之的。然而,如果你傳入了一個可監聽的對象,那麼其對象的 property 還是可響應的。

    //cn.vuejs.org/v2/api/#provide-inject

  8. 全局通訊-事件匯流排

    方法:通過註冊一個新的vue實例作為橋樑,使用$on和$emit來完成通訊

  9. 全局通訊-vuex

    略(看官方文檔嘍)

    //vuex.vuejs.org/zh/

第一種: props傳參

// 父組件向子組件傳遞msg
<template>
  <div>
    <p>我是dad</p>
    <Child :msg="msg" />
  </div>
</template>

<script>
import Child from "./ChildItem.vue";

export default {
  name: "App",
  components: {
    Child,
  },
  data() {
    return {
      msg: "父親的忠告",
    };
  },
};
</script>

// 子組件props接收
<template>
  <div>
    <p>我是子組件</p>
    <span>{{ msg }}</span>
  </div>
</template>

<script>
export default {
  props: {
    msg: {
      type: String,
      default: "什麼都沒有",
    },
  },
};
</script>


第二種:emit,on通訊

// 父組件向子組件提供改變自己狀態的函數
<template>
  <div>
    <p>我是dad</p>
    <Child @changeMyMind="changeMyMind" />
    <span>{{ mind }}</span>
  </div>
</template>

<script>
import Child from "./ChildItem.vue";

export default {
  name: "App",
  components: {
    Child,
  },
  data() {
    return {
      mind: "偉大萬歲",
    };
  },
  methods: {
    changeMyMind(yourMind) {
      this.mind = yourMind;
    },
  },
};
</script>


// 子組件不用接收,直接通過$emit觸發並傳參就行
<template>
  <div>
    <p>我是子組件</p>
  </div>
</template>

<script>
export default {
  mounted() {
    this.$emit("changeMyMind", "躺平鳥");
  },
};
</script>

第三種:$ref,$children實例通訊

// 父組件通過$ref或者$children拿到子組件實例,然後直接修改子組件狀態
/**
 * this.$children`數組中的元素不是響應式的,並且下標並不一定對用父組件引用的子組件的順序,例如有非同步載入的子組件,可能影響其在 children 數組中的順序。所以使用時需要根據一定的條件例如子組件的name去找到相應的子組件。
 **/
<template>
  <div>
    <p>我是dad</p>
    <Child ref="childRef" />
  </div>
</template>

<script>
import Child from "./ChildItem.vue";

export default {
  components: {
    Child,
  },
  mounted() {
    // this.$children[0].childMsg = "不你不是";
    this.$refs.childRef.childMsg = "不你不是";
  },
};
</script>



// 子組件等著被改就行
<template>
  <div>
    <p>我是子組件</p>
    <span>{{ childMsg }}</span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      childMsg: "我是子組件數據",
    };
  },
};
</script>


第四種:$parent通訊

// 父組件
<template>
  <div>
    <p>我是dad</p>
    <Child />
    <span>{{ aa }}</span>
  </div>
</template>

<script>
import Child from "./ChildItem.vue";

export default {
  components: {
    Child,
  },
  data() {
    return {
      aa: "",
    };
  },
  methods: {
    changeAa(data) {
      this.aa = data;
    },
  },
};
</script>

// 子組件通過$parent拿到父組件實例,然後直接修改父組件狀態
<template>
  <div>
    <p>我是子組件</p>
    <span>{{ childMsg }}</span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      childMsg: "我是子組件數據",
    };
  },
  mounted() {
    // this.$parent.aa = "我改了哈"; 不推薦
    this.$parent.changeAa("我改了哦");
  },
};
</script>

第五種:插槽通訊(一般不用)

// 父組件
<template>
  <div>
    <p>我是dad</p>
    <Child>
      <template v-slot:boring>
        {{ aa }}
      </template>
    </Child>
  </div>
</template>

<script>
import Child from "./ChildItem.vue";

export default {
  components: {
    Child,
  },
  data() {
    return {
      aa: "父組件的數據哦",
    };
  },
};
</script>


// 子組件定義插槽
<template>
  <div>
    <p>我是子組件</p>
    <slot name="boring"></slot>
  </div>
</template>

<script>
export default {};
</script>


第六種:$attr,$listener深層雙向通訊

// 父組件
<template>
  <div>
    <p>我是dad</p>
    <span>{{ dadData }}</span>
    <Son :dadData="dadData" @changeDadData="changeDadData" @keyup="someKeyUp" />
  </div>
</template>

<script>
import Son from "./SonItem.vue";

export default {
  components: {
    Son,
  },
  data() {
    return {
      dadData: "父組件的數據哦",
    };
  },
  methods: {
    changeDadData(newData) {
      this.dadData = newData;
    },
    someKeyUp(e) {
      console.log(e.target.value);
    },
  },
};
</script>



// 兒子組件
<template>
  <div>
    <p>我是兒子組件</p>
    <span>{{ $attrs.dadData }}</span>
    <input type="text" v-on="$listeners" />
    <GrandSon v-bind="$attrs" v-on="$listeners" />
  </div>
</template>

<script>
import GrandSon from "./GrandSon.vue";

export default {
  components: {
    GrandSon,
  },
  mounted() {
    console.log(this.$listeners);
  },
};
</script>

// 孫子組件
<template>
  <div>
    <p>我是孫子組件</p>
    <input type="text" @input="grandsonInput" />
  </div>
</template>

<script>
export default {
  methods: {
    grandsonInput(e) {
      //   this.$emit("changeDadData", e.target.value); 也可以觸發
      this.$listeners.changeDadData(e.target.value);
    },
  },
};
</script>



第七種:provide,inject依賴注入深層次單向通訊

// 父組件
<template>
  <div>
    <p>我是dad</p>
    <span>{{ dadMessage }}</span>
    <Son />
  </div>
</template>

<script>
import Son from "./SonItem.vue";

export default {
  components: {
    Son,
  },
  provide() {
    return {
      message: this.dadMessage,
    };
  },
  data() {
    return {
      dadMessage: {
        textContent: "我是個祖先數據",
      },
    };
  },
};
</script>


// 兒子組件
<template>
  <div>
    <p>我是兒子組件</p>
    <span>{{ theData }}</span>
    <GrandSon />
  </div>
</template>

<script>
import GrandSon from "./GrandSon.vue";

export default {
  components: {
    GrandSon,
  },
  inject: {
    // 起個別名
    theData: {
      // 數據來源映射
      from: "message",
      // 默認值
      default: () => ({ message: { textContent: "啥也不是" } }),
    },
  },
};
</script>


// 孫子組件
<template>
  <div>
    <p>我是孫子組件</p>
    <input type="text" @input="grandsonInput" />
    <span>{{ message.textContent }}</span>
  </div>
</template>

<script>
export default {
  methods: {
    grandsonInput(e) {
      this.message.textContent = e.target.value;
    },
  },
  inject: ["message"],
};
</script>



第八種: $bus事件匯流排全局通訊

// 父組件通過this.$bus.$on監聽事件
<template>
  <div>
    <p>我是dad</p>
    <span>{{ dadData }}</span>
    <Son />
  </div>
</template>

<script>
import Son from "./SonItem.vue";

export default {
  components: {
    Son,
  },
  data() {
    return {
      dadData: "我是爹地",
    };
  },
  mounted() {
    this.$bus.$on("changeDadData", this.changeDadData);
  },
  methods: {
    changeDadData(newData) {
      this.dadData = newData;
    },
  },
  // 記得清除監聽
  beforeDestroy() {
    this.$bus.$off("changeDadData");
  },
};
</script>


// 孫子組件通過this.$bus.$emit觸發事件
<template>
  <div>
    <p>我是孫子組件</p>
    <input type="text" @input="grandsonInput" />
    <span></span>
  </div>
</template>

<script>
export default {
  methods: {
    grandsonInput(e) {
      this.$bus.$emit("changeDadData", e.target.value);
    },
  },
};
</script>