组件之间的通信方法总结

父向子传

//父组件
<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>
    
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 父子组件通信 1、父子组件通过prop传递数据 父组件可以将一条数据传递给子组件,这条数据可以是动态的,父组件的数...
    视觉派Pie阅读 5,031评论 0 18
  • 9.1 什么是组件? 组件(Component)是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,...
    白水螺丝阅读 4,223评论 0 2
  • 探讨一下子父组件之间的传值通信问题: 首先是环境搭建: 打开git ,运行 npm install --globa...
    想当一个大头兵阅读 4,270评论 0 0
  • 对于vue来说,组件之间的消息传递是非常重要的,下面是我对组件之间消息传递的各种方式的总结,总共有8种方式。 1....
    edc余悸阅读 2,905评论 0 3
  • 鬼怪里说那地方是U型,从进来的门出去就可以了 生命和生活大抵也是如此 我们从医院小小的病床来到世上,也从医院小小的...
    阿七柒湆戚阅读 1,800评论 0 0