Vue組件之間幾種傳值的方法(看代碼)

簡單額總結一下幾種組件之間的傳參方式

一. props(父傳子)

父組件 傳遞

<template>
  <div>
    <HelloWorld :msg="msg" />
  </div>
</template>
 
<script>
import HelloWorld from "./components/HelloWorld.vue";
 
export default {
  name: "App",
  data() {
    return {
      msg: "需要傳遞給兒子的數據",
    };
  },
  components: {
    HelloWorld,
  },
};
</script> 

子組件 接收

<template>
  <div >
    <h1>{{ msg }}</h1> 
  </div>
</template>
 
<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  }
}
</script>

二. $emit(子傳父)

 子組件 傳遞

<template>
  <div>
    子組件
    <input type="text" v-model="changeVal" />
  </div>
</template>
 
<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      changeVal: "",
    };
  },
  watch: {
    changeVal() {
      this.$emit("childInput", this.changeVal);
    },
  },
};
</script><template>
  <div>
    子組件
    <input type="text" v-model="changeVal" />
  </div>
</template>
 
<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      changeVal: "",
    };
  },
  watch: {
    changeVal() {
      this.$emit("childInput", this.changeVal);
    },
  },
};
</script>

父組件 接收

<template>
  <div>
    父組件{{msg}}
    <HelloWorld @childInput="getVal" />
  </div>
</template>
 
<script>
import HelloWorld from "./components/HelloWorld.vue";
 
export default {
  name: "App",
  data() {
    return {
      msg: "123456",
    };
  },
  methods: {
    getVal(msg) {
      this.msg = msg;
    },
  },
  components: {
    HelloWorld,
  },
};
</script> 

三. $emit $on(非父子)

 1.src文件夾新建common文件夾

2.common文件夾下新建bus.js文件

bus.js 寫這個

import Vue from 'vue'; 
export default new Vue;

兄弟1 傳遞

<template>
  <div>
    第一個 給兄弟的數據是:{{ msg }}
    <button @click="send">點擊傳遞給兄弟數據</button>
  </div>
</template>
 
<script>
import bus from "@/common/bus";
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "6666666666",
    };
  },
  methods: {
    send() {
      bus.$emit("send", this.msg);
    },
  },
};
</script>

兄弟2 接收

<template>
  <div>第二個 {{ msg }}</div>
</template>
 
<script>
import bus from "@/common/bus";
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "",
    };
  },
  mounted() {
    bus.$on("send", (data) => {
      this.msg = data;
    });
  },
};
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章