A detailed explanation of the two-way binding of parent-child value transfer and data update in Vue

Time:2019-12-10

In the process of parent-child component value transfer, the child component is used to directly control the variable value in the parent component and directly change the value of the object or array in Vue. There is no solution for the view to change. At that time, when the project is completed, the reason has not been found and has been modified for a long time.

1. Two way binding of parent-child component value passing

By using the. Sync modifier on the variables passed to the child components, the two-way binding of parent-child values can be realized

<! -- parent component -- >
<template>
 <div>
 <child :show.sync="showModel" @closeModel="handleCloseModel"></child>
 </div>
</template>
<script>
 import child from './child'
 export default{
 components: {
  child,
 }
 data() {
  return {
  showModel: false
  }
 },
 methods: {
  handleCloseModel() {
  this.showModel = false;
  }
 }
 }
</script>
<! -- subcomponent -- >
<template>
 <div @click="handleClick">
 <div></div>
 </div>
</template>
<script>
 export default{
 props: {
  show: Boolean,
 },
 data() {
  return {
  showModel: false
  }
 },
 methods: {
  handleClick() {
  /*Directly update the showmodel value in the parent component*/
  this.$emit('update:show', false);
  /*Or call the method in the parent component to change showmodel*/
  /* this.$emit('closeModel'); */
  }
 }
 }
</script>

2. Modify the key in the object or array, and the view does not change

Use the $set method for modification, which is also described in the official document

At that time, I directly modified the values in the array, but the view did not change

<script>
 export default{
 data() {
  return {
  item: {
   title: '222'
  },
  options: [11, 22],
  list: [
   {
   title: '2222'
   }
  ]
  }
 },
 created() {
  /*For objects, the first is the object to be modified, the second parameter is the key of the object, and the third is the value corresponding to the key to be modified*/
  this.$set(this.item, 'title', '2200');
  /*For objects, the first is the array to be modified, the second parameter is the array index, and the third is the value corresponding to the index to be modified*/
  this.$set(this.options, 0, 33);
  /*For the objects contained in the array, you can use the loop to modify them*/
  this.list.forEach(item => {
  this.$set(item, '_disableExpand', true);
  });
  /*For the objects contained in the array, you can also use object.assign to modify them*/
  this.list[0] = Object.assign({}, this.list[0], { num: 10 });
  this.$set(this.list, 0, this.list[0]);
 },
 }
</script>

You can also force the page to refresh directly after modification, using the $forceupdate () method


this.options[0] = 100;
this.$forceUpdate();

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.