Value transfer between components in vue

Posted by Dm7 on Sat, 05 Mar 2022 07:52:32 +0100

1. Parent child component value transfer

(1) Father to son

The parent component can transfer values to the child component by binding attributes; The child component receives the value passed by the parent component through props. Parent component:

<div class="animal">
        <h2>animal</h2>
        <div>name:{{name1}}</div>
        <div>Age:{{age1}}</div>
        <!-- By binding attributes to the component, the two values are passed through the attributes -->
        <!-- Pass values to sub components through props,In the sub assembly props meet -->
        <Bird :name="name1" :age="age1"></Bird>
  </div>
<script>
import Bird from './Bird.vue'
export default {
  name: "Animal",
  data() {
      return {
          name1:'wild goose',
          age1:20,
      }
  },
  components:{
      Bird
  },
};
</script>

The data defined in the parent component uses the method of binding attributes to bind attributes to the child component labels, Then use props and interpolation expressions in the sub component page to receive data. (the data in props cannot be modified and needs to be transferred) If you want to modify the value passed from the parent component in the child component, if you customize an update function, you can only modify the data of the current page, At this point, you need to use $emit to trigger a custom event. The format is as follows:, updateData in quotation marks here is the name of the custom event, Secondly, myName and myAge of props data transferred in the current page are defined as n and a respectively. Pay attention to the format. There is an object in it.

Sub components:

Receive the value passed by the parent component props:['name','age ']. The child passes to the parent and triggers a custom event this$ emit('updateName',this.myName).

  <div class="bird">
    <h2>birds</h2>
    <div>name:{{ myName }}</div>
    <div>Age:{{ myAge }}</div>
    <button @click="updateData">Modify information</button>
  </div>
<script>
export default {
  name: "Bird",
  props: ["name", "age"],
  data() {
    return {
      myName: this.name,
      myAge: this.age,
    };
  },
  methods: {
    updateData() {
      this.myName = "Red-crowned crane";
      this.myAge = 10;
      // By passing values to parent components, you can trigger custom events through $emit
      this.$emit("updateData", {n: this.myName,a: this.myAge});
    },
  },
};
</script>

Note: the data in props cannot be modified. =>>>That is, you can't write methods directly in methods, Methods: {updatedata() {this. Name = 'crane' this.age = 10}} Σ (° △° |) ︴

then Add @ updateData="updateData" to the child page label in the parent page, The previous updateData is the name of the custom event in the sub page, The following updateData is the name of a function defined for the current page, Then then Define the method in methods, where e is the data passed from the child page to the parent page, and finally modify the data of the current page.

  <div class="animal">
        <h2>animal</h2>
        <div>name:{{name1}}</div>
        <div>Age:{{age1}}</div>
        <Bird :name="name1" :age="age1" @updateData="updateData"></Bird>
  </div>
<script>
import Bird from './Bird.vue'
export default {
  name: "Animal",
  data() {
      return {
          name1:'wild goose',
          age1:20
      }
  },
  components:{
      Bird
  },
  methods: {
      updateData(e){
          this.name1 = e.n
          this.age1 = e.a
      }
  },
};
</script>

2. Value transfer of grandparent components

First of all, the value passed from ancestors to future generations can also be passed by props, layer by layer. If five or six layers are nested, this method is very cumbersome. Therefore, provide and inject are used. These two are used together to allow ancestors to inject a dependency into all ancestral offspring. Ancestor components add dependent data through provide, and the data defined in it can be selectively injected and directly used by descendant components through inject. Note: the descendant component injects the dependent data in the ancestor component through inject. Like props, the received data is read-only and cannot be modified.

Ancestor component:

<div class="animal">
  <div>name:{{ name2 }}</div>
  <div>Age:{{ age2 }}</div>
  <Bird :name="name1" :age="age1" ></Bird>
</div>
data() {
  return {
    name2: "Xiao Ming",
    age2: 5
  };
}
// Add dependent data. The data defined in it can be selectively injected and directly used by sub components.
provide() {
  return {
    doveName: this.name2,
    doveAge: this.age2,
    // Set the method of modifying name2 and age2 as dependent data
    updateDove: this.updateDove,
  };
},
methods: {
  updateDove(dove) {
    this.name2 = dove.name;
    this.age2 = dove.age;
  },
}

Descendant components:

<div class="dove">
  <h2>dove</h2>
  <div>name:{{ mydoveName }}</div>
  <div>Age:{{ mydoveAge }}</div>
  <button @click="updateData">Modify data</button>
</div>
// Inject dependent data from parent components
inject: ["doveName", "doveAge", "updateDove"],
data() {
  return {
    mydoveName: this.doveName,
    mydoveAge: this.doveAge,
  };
},
methods: {
  updateData() {
    this.mydoveName = "Xiao Hong";
    this.mydoveAge = 8;
    // Execute the updateDove method in the parent component
    this.updateDove({ name: this.mydoveName,age: this.mydoveAge, });
  }
}

3. Sibling component value transfer

On the Vue prototype object, add a $bus attribute whose attribute value is a Vue instance. All instances of Vue will share the same $bus. This $bus attribute is called the central event bus.

In vue's entry file main JS,

Vue.prototype.$bus = new Vue()

Write in two sibling components respectively,

methods: {
    // Method of modifying crow information
    updateCrow(){
        this.$bus.$emit('updateCrow',{name:'Xiao Wang',age:30})
    }
},
mounted() {
    // Listen to the updateCrow event. When this event is triggered, the corresponding callback function will be executed
    this.$bus.$on('updateCrow',(e)=>{
      this.name=e.name
      this.age=e.age
    })
  },