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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章