Vue2與Vue3的組件通訊對比

Vue2

父傳子

父傳子比較簡單, 主要通過以下步驟實現

  1. 父在template中為子綁定屬性

    <Child :childData='pMsg'/>
    <!-- 也可以寫死 -->
    <Child childData='123'/>
    
  2. 子用props接收數據, props的值可以是數組或對象

    props: ["childData"]
    
  3. 子在template中或其他地方任意使用接受到的數據

    <h2>我得到了{{childData}}</h2>
    

列出完整例子:

<!--@html-start-->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>title</title>
    </style>
  </head>
  <body>
    <div id="app">{{ message }}</div>

    <script src="//cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  </body>
</html>

<!--@html-end-->

<!--@css-start-->
fieldset {
	margin-top: 30px;
}
<!--@css-end-->

<!--@javascript-start-->
Vue.component("Parent", {
  data() {
    return {
      pMsg: "小樓昨夜又東風",
    };
  },
  //步驟一
  template: `<div><fieldset><legend>父組件</legend><input type="text" v-model="pMsg"/><Child :childData='pMsg'/></fieldset></div>`,
});
Vue.component("Child", {
  //步驟三
  template: `<div><fieldset><legend>子組件</legend>來自父組件的數據: {{ childData }}</fieldset></div>`,
  //步驟二
  props: ["childData"],
});
var vm = new Vue({
  el: "#app",
  data() {
    return {
      msg: "往input中輸入東西試試",
    };
  },
  template: `<div><fieldset><legend>App組件</legend>{{ msg }}<Parent/></fieldset></div>`,
});
<!--@javascript-end-->

子傳父

  1. 父組件中為子組件綁定一個自定義事件
    <h2> <Child @childHandler="childHandler" /></h2>`
    
  2. 父組件中為自定義事件寫函數,形參為要接收的值,假如要加到this中的話,最好在data中預留一個key
    methods: {
    	childHandler(val) {
    		this.ChildData = val
    	}
    }
    
  3. 子組件中綁定一個原生事件
    @input="change(data)"
    

    再在方法中使用$emit調用父組件中的方法

    this.$emit("childHandler", val)
    

    觸發父組件中的自定義事件

    $emit: 觸發當前實例上的事件。附加參數都會傳給監聽器回調

完整例子:

<!--@html-start-->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>title</title>
  </head>
  <body>
    <div id="app">{{ message }}</div>

    <script src="//cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  </body>
</html>

<!--@html-end-->
<!--@css-start-->
fieldset {
	margin-top: 30px;
}
<!--@css-end-->
<!--@javascript-start-->
Vue.component("Parent", {
  data() {
    return {
      ChildData: "",
    };
  },
  //步驟一
  template: `<div><fieldset><legend>父組件</legend><p>來自子組件的數據: {{ ChildData }}</p><Child @childHandler="childHandler" /></fieldset></div>`,
  // 步驟二
  methods: {
    // 處理從子組件中獲取的數據
    childHandler(val) {
      this.ChildData = val;
    },
  },
});
Vue.component("Child", {
  data() {
    return {
      data: "故國不堪回首月明中",
    };
  },
  //步驟三
  template: `<div><fieldset><legend>子組件</legend><input type="text" v-model="data" @input="change(data)" /></fieldset></div>`,
  methods: {
    // 調用$emit方法
    change(val) {
      this.$emit("childHandler", val);
    },
  },
});
var vm = new Vue({
  el: "#app",
  data() {
    return {
      msg: "在input中輸入東西試試",
    };
  },
  template: `<div><fieldset><legend>App組件</legend>{{msg}}</h1><Parent/></fieldset></div>`,
});

<!--@javascript-end-->

父傳孫

父組件里使用provide, 子組件里使用inject
完整例子

<!--@html-start-->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>title</title>
  </head>
  <body>
    <div id="app">{{ message }}</div>

    <script src="//cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  </body>
</html>
<!--@html-end-->

<!--@javascript-start-->
Vue.component("Parent", {
  data() {
    return { data: "小樓昨夜又東風" };
  },
  template: `<div><fieldset><legend>父組件</legend><p>父組件數據: {{ data }}</p><Child /></fieldset></div>`,
  // 步驟一
  provide() {
    return {
      data: this.data,
    };
  },
});
Vue.component("Child", {
  template: `<div><fieldset><legend>子組件</legend><GrandSon /></fieldset></div>`,
});
Vue.component("GrandSon", {
  // 步驟二
  // 接收祖輩的數據 data
  inject: ["data"],
  data() {
    return {
      // 通過this.x取值
      parentData: this.data,
    };
  },
  template: `<div><fieldset><legend>孫組件</legend><p>祖輩的數據: {{ parentData }}</p></fieldset></div>`,
});
var vm = new Vue({
  el: "#app",
  data() {
    return {
      msg: "觀察組件的數據",
    };
  },
  template: `<div><fieldset><legend>App組件</legend><p>{{ msg }}</p><Parent/></fieldset></div>`,
});

<!--@javascript-end-->
<!--@css-start-->
fieldset {
	margin-top: 30px;
}
<!--@css-end-->

注意, 這種方法傳值不是響應數據
你可以把數據變為object類型, 讓其可以同步修改

兄弟之間互傳

  1. 在Vue的原型對象向上添加一個屬性叫$bus
    該屬性是一個Vue實例對象
  2. 發送端, 調用this.$bus.$emit
  3. 接收端, 監聽對應事件, 處理數據

完整例子:

<!--@html-start-->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>title</title>
  </head>
  <body>
    <div id="app">{{ message }}</div>

    <script src="//cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  </body>
</html>
<!--@html-end-->
<!--@javascript-start-->
// 步驟一 添加$bus屬性
Vue.prototype.$bus = new Vue();

Vue.component("Child1", {
  data() {
    return { data: "小樓昨夜又東風" };
  },
  methods: {
    update() {
      // 步驟二 使用$emit觸發自定義事件, 傳入數據
      this.$bus.$emit("handlerData", this.data);
    },
  },
  template: `<div><fieldset><legend>子組件</legend><p>子組件發送的數據:  <input type="text" v-model="data" @input="update()"/></p></fieldset></div>`,
});
Vue.component("Child2", {
  data() {
    return {
      data: "",
    };
  },
  mounted() {
    // 步驟三 處理傳過來的數據
    this.$bus.$on("handlerData", (val) => {
      this.data = val;
    });
  },
  template: `<div><fieldset><legend>子組件</legend><p>子組件接收的數據: {{ data }}</p></fieldset></div>`
});
var vm = new Vue({
  el: "#app",
  data() {
    return {
      msg: "往input中輸入數據試試",
    };
  },
  template: `<div><fieldset><legend>App組件</legend><p>{{msg}}</p><Child1 /> <Child2 /></fieldset></div>`,
});
<!--@javascript-end-->
<!--@css-start-->
fieldset {
	margin-top: 30px;
}
<!--@css-end-->

Vue3

由於vue3vue2的選項變為了組合API, 而且把datamethods集合到了setup中, 故而使用起來有所區別, 但也大差不差

父傳子

  1. 父組件使用refreactive將數據變為響應數據
  2. 子組件使用props接收

    關於props見: props

  3. 要在setup中使用, 使用如下方法:
    props: ["data"],
    setup(props, context) {
      props.data
    }
    

完整例子

<!--@html-start-->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>title</title>
  </head>
  <body>
    <div id="app">
      <fieldset>
        <legend>app組件</legend>
        {{ data }}
        <!-- 使用組件 -->
        <Parent />
      </fieldset>
    </div>

    <script src="//unpkg.com/[email protected]/dist/vue.global.js"></script>
  </body>
</html>
<!--@html-end-->
<!--@javascript-start-->
const AttributeBindingApp = {
  name: "App",
  setup() {
    const data = "往input中輸入東西試試";
    return {
      data,
    };
  },
};
const app = Vue.createApp(AttributeBindingApp);
app.component("Parent", {
  setup() {
    // 變為響應數據
    const parentData = Vue.ref("故國不堪回首月明中");
    return {
      parentData,
    };
  },
  template: `<fieldset><legend>父組件</legend> <input type="text" v-model="parentData" /> <Child :parentData="parentData" /></fieldset>`,
});
app.component("Child", {
  props: ["parentData"],
  setup() {
    const childData = "childData";

    return {
      childData,
    };
  },
  template: `<fieldset><legend>子組件</legend>{{ parentData }}</fieldset>`,
});
app.mount("#app");

<!--@javascript-end-->
<!--@css-start-->
fieldset {
	margin-top: 30px;
}
<!--@css-end-->

子傳父

  1. 父組件中定義接收數據的方法
  2. template中為子組件綁定自定義事件
  3. 在子組件中觸發自定義事件, 執行context.emit方法
  4. 傳給父組件使用

總的來說, 原理與Vue2差不多, 但由於要在setup中獲取值, 故要使用參數接收

<!--@html-start-->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>title</title>
  </head>
  <body>
    <div id="app">
      <fieldset>
        <legend>app組件</legend>
        {{ data }}
        <!-- 使用組件 -->
        <Parent />
      </fieldset>
    </div>

    <script src="//unpkg.com/[email protected]/dist/vue.global.js"></script>
  </body>
</html>
<!--@html-end-->
<!--@javascript-start-->
const AttributeBindingApp = {
  name: "App",
  setup() {
    const data = "往input中輸入東西試試";
    return {
      data,
    };
  },
};
const app = Vue.createApp(AttributeBindingApp);
app.component("Parent", {
  setup(props, context) {
    const childData = Vue.ref("");
    // 步驟一 定義處理接收數據的方法
    const receive = (e) => {
      // 處理從子組件中傳來的數據

      childData.value = e;
    };
    return {
      receive,
      childData,
    };
  },
  // 步驟二 自定義事件 觸發處理接收數據的方法
  template: `<fieldset><legend>父組件</legend><p>子組件中的數據: {{ childData }}</p><Child @inputText="receive" /></fieldset>`,
});
app.component("Child", {
  props: ["parentData"],

  setup(props, context) {
    const data = Vue.ref("小樓昨夜又東風");
    // 步驟四 調用context.emit
    const toParent = () => {
      // input時調用
      // 調用inputText事件

      context.emit("inputText", data.value);
    };
    return {
      data,
      toParent,
    };
  },
  // 步驟三 觸發事件
  template: `<fieldset><legend>子組件</legend><input type="text" @input="toParent" v-model="data" /></fieldset>`,
});
app.mount("#app");
<!--@javascript-end-->
<!--@css-start-->
fieldset {
	margin-top: 30px;
}
<!--@css-end-->

父傳孫

和vue2一樣, 同樣使用provideinject
但不同的是, 我們可以使用refreactive將數據轉換為響應式數據

<!--@html-start-->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>title</title>
  </head>
  <body>
    <div id="app">
      <fieldset>
        <legend>app組件</legend>
        {{ data }}
        <!-- 使用組件 -->
        <Parent />
      </fieldset>
    </div>

    <script src="//unpkg.com/[email protected]/dist/vue.global.js"></script>
  </body>
</html>

<!--@html-end-->
<!--@javascript-start-->
const AttributeBindingApp = {
  name: "App",
  setup() {
    const data = "往兩個input中都輸入試試";
    return {
      data,
    };
  },
};
const app = Vue.createApp(AttributeBindingApp);
app.component("Parent", {
  setup() {
    // 響應的數據
    const data = Vue.ref("");
    // 步驟一 使用provide
    // 把data 標記為 "parentData"
    Vue.provide("parentData", data);
    return {
      data,
    };
  },
  template: `<fieldset><legend>父組件</legend>從子孫輩中獲取的數據: <input type="text" v-model="data" /> <Child /></fieldset>`,
});
app.component("Child", {
  template: `<fieldset><legend>子組件</legend><GrandSon /></fieldset>`,
});
app.component("GrandSon", {
  setup() {
    // 步驟二 接收數據
    // 接收 parentData
    const data = Vue.inject("parentData");
    return {
      data,
    };
  },
  template: `<fieldset><legend>孫組件</legend><p>從父輩中獲取的數據: <input type="text" v-model="data" /></p></fieldset>`,
});
app.mount("#app");

<!--@javascript-end-->

<!--@css-start-->
fieldset {
	margin-top: 30px;
}
<!--@css-end-->

Tags: