美文网首页
组件之间的通信方法总结

组件之间的通信方法总结

作者: wwg9311 | 来源:发表于2020-03-08 17:55 被阅读0次

父向子传

//父组件
<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>
    

相关文章

  • 组件之间的通信方法总结

    父向子传 方法总结 在子组件中绑定自定义属性来接收父组件的数据值 在子组件的模板中通过props来接收父组件的传值...

  • vue中8种组件通信方式, 值得收藏!

    之前写了一篇关于vue面试总结的文章, 有不少网友提出组件之间通信方式还有很多, 这篇文章便是专门总结组件之间通信...

  • 自己总结的Angular2组建通信

    组件之间的通信 这里简单的记录自己在angular2中,使用组件通信的一些方法。方便自己以后的使用。 一、组件之间...

  • vue父组件调用子组件的方法

    vue组件与组件通信有如下几种情况: 平行组件父组件与子组件子组件与父组件 它们之间通信有几种方法有: props...

  • Vue 组件间通信

    背景 在使用 Vue 时,经常会有父子组件之间的通信需求,有很多种方法可以实现。 实现 父组件向子组件通信 方法一...

  • Vue组件通信、双向绑定

    一、组件之间的通信 父组件向子组件传递 props this.$parents应急方法(包括$children) ...

  • React的组件通信

    组件之间进行通信的情况: 父组件向子组件通信 子组件向父组件通信 兄弟组件之间通信 发布者-订阅者模式 一、父组件...

  • 使用React Native写页面踩过的坑

    1.组件之间通信 子组件调用父组件的方法:子组件要拿到父组件的属性,需要通过this.props方法。每次父组件修...

  • 老生常谈——vue组件之间通信

    老生常谈的组件之间通信 vue组件之间的通信细分为三种情况:兄弟组件之间的通信,父组件向子组件传递数据,子组件向父...

  • [Vue]组件之间如何通信?

    组件通信可以大致分为两种情况,父子组件之间的通信和非父子组件之间的通信,下面来分别介绍 一、父子组件之间的通信 1...

网友评论

      本文标题:组件之间的通信方法总结

      本文链接:https://www.haomeiwen.com/subject/sfljdhtx.html