组件之间的通信方法总结

2020-03-08  本文已影响0人  wwg9311

父向子传

//父组件
<template>
  <div class="father">
    <Son :message="fatherMsg" />
  </div>
</template>

<script>
import Son from "@/components/Son.vue";
export default {
  name: "Father",
  data() {
    return {
      fatherMsg: "父组件数据"
    };
  },
  components: {
    Son
  }
};
</script>

//子组件
<template>
  <div class="son">
    <p>{{message}}</p>
  </div>
</template>

<script>
export default {
  name: "Son",
  data() {
    return {};
  },
  props: {
    message: String
  }
};
</script>
方法总结
  1. 在子组件中绑定自定义属性来接收父组件的数据值

    <Son :message="fatherMsg" />
    
  2. 在子组件的模板中通过props来接收父组件的传值

    props:{
     message:String//声明数据类型,需要与绑定的自定义属性名一致
    }
    或者
    props:["message"]
    
  3. 在子组件中调用数据

    <p>{{message}}</p>
    

子向父传

//父组件
<template>
  <div class="father">
    <Son @sendToFather="getDate" />
    <p>{{fatherMsg}}</p>
  </div>
</template>

<script>
import Son from "@/components/Son.vue";
export default {
  name: "Father",
  data() {
    return {
      fatherMsg: ""
    };
  },
  components: {
    Son
  },
  methods: {
    getDate: function(val) {
      this.fatherMsg = val;
    }
  }
};
</script>

//子组件
<template>
  <div class="son">
    <button @click="sendMsg">向父组件传值</button>
  </div>
</template>

<script>
export default {
  name: "Son",
  data() {
    return {
      sonMsg: "子组件数据"
    };
  },
  methods: {
    sendMsg: function() {
      //核心部分
      this.$emit("sendToFather", this.sonMsg);
    }
  },
  mounted() {
    //核心部分
    this.$emit("sendToFather", this.sonMsg);
  }
};
</script>
方法总结
  1. 在子组件的模板中的某个标签上绑定事件或者在组件生命周期中来触发自定义事件,注意,必须通过**emit**来调用自定义事件,this.emit("自定义事件名",子组件的数据)

    this.$emit("sendToFather",this.sonMsg)
    
  2. 在子组件中绑定自定义的事件来触发父组件的方法

    <Son @sendToFather="getDate">
    
  3. 在父组件的methods里面声明“getDate”方法,并进行数据赋值

    methods: {
     getDate: function(val) {
         this.fatherMsg = val;
     }
    }
    
  4. 在父组件中调用数据

    <p>{{fatherMsg}}</p>
    
上一篇 下一篇

猜你喜欢

热点阅读