Example of data transfer between Vue 2.0 components

  • 2021-07-26 06:53:23
  • OfStack

Vue 1.0 Component-to-Component Transfer

Listen for events using $on (); Use $emit () to fire events on it; Use $dispatch () to distribute events, which bubble along the parent chain; Use $broadcast () to broadcast events, which are propagated down to all descendants

After Vue2.0, $dispatch () and $broadcast () were abandoned. See https://cn.vuejs.org/v2/guide/migration.html # dispatch-and-broadcast-Replacement

1. Parent component passes scenario to child component: 1 input box on Father, which is passed to Child component according to the input.

Parent component:


<template>
 <div>
  <input type="text" v-model="msg">
  <br>
  // Set the child control property inputValue Parent component msg Attribute binding 
  <child :inputValue="msg"></child>
 </div>
</template>
<style>

</style>
<script>
 export default{
  data(){
   return {
    msg: ' Please enter '
   }
  },
  components: {
   child: require('./Child.vue')
  }
 }
</script>

Subcomponents:


<template>
 <div>
  <p>{{inputValue}}</p>
 </div>
</template>
<style>

</style>
<script>
  export default{
    props: {
     inputValue: String
    }
  }
</script>

2. Scenario of value transfer from subcomponent to parent component: Input box on subcomponent, pop-up box when parent component listens after input value changes

Parent component:


<template>
 <div>
//message Notifications bound to child controls; recieveMessage Method after listening for parent component 
  <child2 v-on:message="recieveMessage"></child2>
 </div>
</template>
<script>
 import {Toast} from 'mint-ui'
 export default{
  components: {
   child2: require('./Child2.vue'),
   Toast
  },
  methods: {
   recieveMessage: function (text) {
    Toast(' Listening for subcomponent changes '+text);
   }
  }
 }
</script>

Subcomponents:


<template>
 <div>
  <input type="text" v-model="msg" @change="onInput">
 </div>
</template>
<script>
 export default{
  data(){
   return {
    msg: ' Please enter a value '
   }
  },
  methods: {
   onInput: function () {
    if (this.msg.trim()) {
     this.$emit('message', this.msg);
    }
   }
  }
 }
</script>

Related articles: