Home  >  Q&A  >  body text

Destructuring reactive objects in Vue script settings

I'm following the Vue 3 documentation to see how I can move to using the <script setup> tag to simplify my component code.

One of the benefits of using this setting is that you no longer need to use the export default boilerplate to explicitly return objects: anything declared in the top-level scope will be automatically available in the template.

The problem I have is that in my application I have a very large object as my initial state, in my normal Vue 3 application I can return the object and have it automatically destructured as follows Shown:

<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>

This saves me from having to declare each item in the object as its own ref(), thus removing boilerplate.

My question is, how can I achieve the same automatic destructuring in Vue mode, which only detects top-level declarations? I'd like to be able to reference the object's keys directly without having to use state.foo or state.bar, but without having to explicitly declare each key as const in order to make it available in

<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>

P粉418214279P粉418214279207 days ago439

reply all(1)I'll reply

  • P粉761718546

    P粉7617185462024-03-26 18:19:46

    You can destructure the object as you do now and save the remaining object keys and values ​​using the spread operator.

    sssccc

    Every key except foo and bar can be accessed by accessing the remaining variables. Like rest.test

    If this isn't what you want, I don't think what you're trying to do is possible.

    If my answer is not what you want, please see this article: How to destructure into dynamically named variables in ES6?

    reply
    0
  • Cancelreply