使用 prop 的值作为组件中可变数据的基础

use prop's value as basis for mutable data in component

假设在 vue 3 组件中我有以下内容

<script>
export default {
  props: {
    minimumDays: Number
  },
  data() {
      return {
        days: this.minimumDays + Math.ceil(Math.random() * 40)
      }
  },
  methods: {
    increaseDays() {
      this.days = this.days + 1
    }
  }
}
</script>

如您所见,我正在使用道具的值来计算名为“days”的可变 'data' 变量的初始值。我首先尝试使用 computed 对象来执行此操作,但收到一条错误消息,指示不应更改计算数据。

这样可以接受,在data的建立中引用一个prop吗?是否有正确的技术从 prop 中获取一些数据,并在修改后使用它在组件中建立可变状态?

如果您知道 prop 中的更改不会反映在 child 中,那没关系。这包括如果 prop 数据是异步的 and/or 在创建 child 组件时未定义。这样做意味着在创建 child 组件之前复制一次道具。

如果这不是你想要的,那么你可以使用计算和可变数据 属性:

props: {
  minimumDays: Number
},
data() {
  return {
    adjustableDays: Math.ceil(Math.random() * 40)
  }
},
computed: {
  days() {
    return this.minimumDays + this.adjustableDays;
  }
},
methods: {
  increaseDays() {
    this.adjustableDays = this.adjustableDays + 1
  }
}

这是一个演示:

Vue.component('child', { 
  template: `
  <div>
    Adjustable: {{ adjustableDays }}<br>
    Total: {{ days }}<br>
    <button @click="increaseDays">Increase Adjustable (in Child)</button>
  </div>
  `,
  props: {
    minimumDays: Number
  },
  data() {
    return {
      adjustableDays: Math.ceil(Math.random() * 40)
    }
  },
  computed: {
    days() {
      return this.minimumDays + this.adjustableDays;
    }
  },
  methods: {
    increaseDays() {
      this.adjustableDays = this.adjustableDays + 1
    }
  }
})

new Vue({
  el: "#app",
  data() {
    return {
      min: 15
    }
  }
});
<div id="app">
  Minimum: {{ min }}
  <child :minimum-days="min"></child>
  <button @click="min++">Increase Minimum (in Parent)</button>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>