gpt4 book ai didi

vue.js - 在 Vue 脚本设置中解构 Reactive 对象

转载 作者:行者123 更新时间:2023-12-05 04:32:47 25 4
gpt4 key购买 nike

我正在关注有关如何使用 <script setup> 的 Vue 3 文档标签来简化我的组件代码。

使用此设置的好处之一是您不再需要使用导出默认样板来显式返回对象:在顶级范围内声明的任何内容都将自动在模板中可用。

我遇到的问题是,在我的应用程序中,我有一个非常大的对象作为我的初始状态,在我的普通 Vue 3 应用程序中,我可以返回并自动解构,如下所示:

<script>
import { reactive, toRefs } from 'vue'

export default {
setup() {
const state = reactive({
foo: 1,
bar: 2,
// the rest of a very large object
})

return toRefs(state)
}
}
</script>

这让我不必将对象中的每一项都声明为它自己的 ref(),从而消除了样板文件。

我的问题是,如何在 Vue 模式下实现相同的自动解构,它只检测顶级声明?我希望能够直接引用对象的键,而不必使用 state.foo 或 state.bar,但不必为了使其在

<script setup>
import { reactive, toRefs } from 'vue'

const state = reactive({
foo: 1,
bar: 2,
// the rest of a very large object
})

const { foo, bar, ? } = toRefs(state) // how do I destructure this dynamically?
</script>

最佳答案

您可以像现在一样解构您的对象,并使用扩展运算符保存其余的对象键和值。

<script setup>
import { reactive, toRefs } from 'vue'

const state = reactive({
foo: 1,
bar: 2,
test: 'test',
// the rest of a very large object
})

const { foo, bar, ...rest } = toRefs(state) // how do I destructure this dynamically?
</script>

除了 foo 和 bar 之外的每个键都可以通过访问 rest 变量来访问。喜欢rest.test

如果这不是您想要的,我认为您尝试做的事情是不可能的。

如果我的回答不是您要找的,请参阅这篇文章: How to destructure into dynamically named variables in ES6?

关于vue.js - 在 Vue 脚本设置中解构 Reactive 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71596737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com