vue父子组件传值,父组件内容更新子组件内容不实时更新

背景:vue父子组件传值不能实时更新问题,父组件将值传给了子组件,但子组件显示的值还是原来的初始值,并没有实时更新

总结了以下三种情况及解决方案

1. 子组件没有正确监听父组件传递的值:在子组件中,确保正确地声明了props,并且监听了父组件传递的值。

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

2. 父组件没有正确地传递新的值给子组件:在父组件中,确保正确地更新了传递给子组件的值。

<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. 子组件中的值没有正确地更新:在子组件中,确保在正确的时机更新了值,例如在计算属性中使用父组件传递的值。

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

猜你喜欢

转载自blog.csdn.net/gjwgjw1111/article/details/132686894
今日推荐