Vue 父组件 Props 变化,子组件值不更新?三种解决方法
如果父组件的 Props 值改变了,但子组件的值没有更新,可能有以下几种解决方法:
- 使用 Vue 的'watch'属性来监听父组件 Props 的变化,在监听到变化时手动更新子组件的值。例如:
// 子组件
export default {
  props: ['value'],
  watch: {
    value: function(newVal) {
      this.myValue = newVal;
    }
  },
  data() {
    return {
      myValue: this.value
    }
  }
}
- 在子组件中使用计算属性来获取父组件 Props 的值,这样在父组件 Props 变化时,子组件的计算属性会自动更新。例如:
// 子组件
export default {
  props: ['value'],
  computed: {
    myValue: function() {
      return this.value;
    }
  }
}
- 使用'$emit'方法在父组件中监听 Props 的变化,并通过事件将新的值传递给子组件。例如:
// 父组件
<template>
  <div>
    <button @click="changeValue">改变值</button>
    <ChildComponent :value="parentValue" @update-value="updateValue"></ChildComponent>
  </div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
  data() {
    return {
      parentValue: '初始值'
    }
  },
  methods: {
    changeValue() {
      this.parentValue = '新的值';
    },
    updateValue(newVal) {
      this.parentValue = newVal;
    }
  },
  components: {
    ChildComponent
  }
}
</script>
// 子组件
<template>
  <div>
    <p>{{ myValue }}</p>
  </div>
</template>
<script>
export default {
  props: ['value'],
  computed: {
    myValue: function() {
      return this.value;
    }
  },
  watch: {
    value: function(newVal) {
      this.$emit('update-value', newVal);
    }
  }
}
</script>
以上是几种常见的解决方法,根据具体情况选择适合的方式来更新子组件的值。
原文地址: https://www.cveoy.top/t/topic/qg0P 著作权归作者所有。请勿转载和采集!