Vue parent-child components pass values, the content of the parent component is updated and the content of the child components is not updated in real time

Background: Vue parent-child component values ​​cannot be updated in real time. The parent component passes the value to the child component, but the value displayed by the child component is still the original initial value, and it is not updated in real time.

The following three situations and solutions are summarized

1. The child component does not correctly monitor the value passed by the parent component: In the child component, make sure to declare the props correctly and listen to the value passed by the parent component.

<template>
  <div>
    <span>{
   
   { value }}</span>
  </div>
</template>
<script>
export default {
      
      
  props: ['value'],
  watch: {
      
      
    value(newValue) {
      
      
      // 在这里处理新值的更新逻辑
    }
  }
};
</script>

2. The parent component does not pass the new value to the child component correctly: In the parent component, make sure to update the value passed to the child component correctly.

<template>
  <div>
    <child-component :value="parentValue"></child-component>
    <button @click="updateParentValue">更新父组件的值</button>
  </div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
      
      
  components: {
      
      
    ChildComponent
  },
  data() {
      
      
    return {
      
      
      parentValue: '初始值'
    };
  },
  methods: {
      
      
    updateParentValue() {
      
      
      this.parentValue = '更新后的值';
    }
  }
};
</script>

3. The value in the child component is not updated correctly: In the child component, make sure to update the value at the right time, such as using the value passed by the parent component in the calculated property.

<template>
  <div>
    <span>{
   
   { computedValue }}</span>
  </div>
</template>
<script>
export default {
      
      
  props: ['value'],
  computed: {
      
      
    computedValue() {
      
      
      // 在这里根据父组件传递的值计算出新的值
      return this.value + '(经过计算后的新值)';
    }
  }
};
</script>

Guess you like

Origin blog.csdn.net/gjwgjw1111/article/details/132686894