父傳子
首先,在父組件的頁面中引入子組件。
message爲名字(隨意取),problemTitle爲父組件裏面的屬性,即需要向子組件傳的值。
父組件中代碼:
<children :message="problemTitle"></children>
子組件代碼:
props: ["message"]
(不要寫在data中)(message爲在父組件中取得名字)
子傳父
子組件需要向父組件拋發一個值
子組件代碼:
this.$emit("showProblemDetail", this.qs) (showProblemDetail爲起的名字)
父組件代碼:
<BeginToUse v-on:showProblemDetail="getMsgFormSon"></BeginToUse> (showProblemDetail爲在子組件中起的名字)
methods:{
getMsgFormSon (data) {
data爲子組件拋發的值
},
}
兄弟組件傳值
兄弟組件傳值通過bus,即vue實例
首先,需要建一個bus.js。
內部代碼如下:
import Vue from "vue";
export default new Vue();
需要傳值的組件代碼如下:
Bus.$emit("txtStatus", "3");
txtStatus爲名字
接收傳值的代碼如下:
Bus.$on("txtStatus", function (val) {
val即爲傳過來的值
});
注意:bus指向vue實例,與當前組件的this指向不同!!!