vue3 props 是对象的情况如何变为响应式?

如题,定义一个组件,设置 props 如下:

interface Props {
  decorateConfig: {
    'src'?: string
  },
  width?: number,
  height?: number
}
const props = withDefaults(defineProps<Props>(), {
  decorateConfig: () => {
    return {
      src: ''
    }
  }
})

当我直接定义

const src = props.decorateConfig.src

的时候,会提示这样会失去响应性

Getting a value from the `props` in root scope of `<script setup>` will cause the value to lose reactivity.

所以想问下,如何可以将这样的定义,转为响应性

阅读 2.5k
avatarAI BotBETA

在 Vue 3 中,要在组件中保持属性的响应性,你应该使用 reactive 函数来创建响应式对象。这样,当你的属性发生变化时,Vue 就会更新组件的渲染。

你可以像下面这样来修改你的代码:

import { reactive } from 'vue'

interface Props {
  decorateConfig: {
    src?: string
  },
  width?: number,
  height?: number
}

const props = withDefaults(defineProps<Props>(), {
  decorateConfig: () => {
    return {
      src: ''
    }
  }
})

// 创建一个响应式对象,包含所有属性
const instance = reactive(props)

// 现在你可以通过 `instance.decorateConfig.src` 来访问属性,并且它们是响应式的
const callImg = instance.decorateConfig.src

在上面的代码中,我们首先导入了 reactive 函数,然后使用它来创建一个新的响应式对象 instance,该对象包含了所有的属性。然后我们可以通过这个响应式对象来访问所有的属性,并且这些属性都是响应式的。这意味着当这些属性的值发生变化时,Vue 会自动更新组件的渲染。

1 个回答

render function 外部访问 props 的值,还想保留响应式的话,需要用 computed 来处理

const src = computed(() => props.decorateConfig.src)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题