将 prop 对象传递给 ref() 以对其进行修改是否安全?

Is it safe to pass a prop object to `ref()` for it to be modified?

在 Vue 3 中,我可以从作为要在我的组件中修改的对象的 prop 创建 ref 吗?

<template>
  <button @click.prevent="increment">You've clicked me {{ countObj.count }} times</button>
</template>

<script>
import { defineComponent, ref } from 'vue'

export default defineComponent({
  props: {
    startingCount: {
      type: Object,
      default: () => ({
        count: 0
      })
    }
  },

  setup (props) {
    const countObj = ref(props.startingCount)
    const increment = () => {
      countObj.value.count++
    }

    return {
      countObj,
      increment,
    }
  }
})
</script>

修改countObj时我的道具是否也会被修改?

简短的回答是肯定的! startingCountcountObj 属性都会被修改。

更有趣的是,如果父组件为 startingCount prop 传递一个响应式对象,那么父组件上的响应式也会发生响应式变化! See it live


但这被认为是一种不好的做法。你不应该直接修改道具。 来自文档:

All props form a one-way-down binding between the child property and the parent one: when the parent property updates, it will flow down to the child, but not the other way around. This prevents child components from accidentally mutating the parent's state, which can make your app's data flow harder to understand.

为了对父组件执行变更,您可以 emit an event

阅读有关 One-way data flow 的更多信息,包括 Mutating Object / Array Props 的用例。


在您的情况下,为了解决道具突变问题,请替换为:

const countObj = ref(props.startingCount)

与:

const countObj = ref({ count: props.startingCount.count })