Home > Back-end >  Using script setup and reactive state vue 3 with toRefs
Using script setup and reactive state vue 3 with toRefs

Time:12-14

I'm trying to use script setup in my vue project.

Before using script setup, my script would be like this:

<script>
import Layout from '../containers/Layout.vue';
import { reactive, toRefs } from 'vue'

export default {
    name: 'Home',
    setup() {
        const state = reactive({});
        return {
            ...toRefs(state),
        };
    },
    components: { Layout, Layout }
}
</script>

Now I have it like this:

<script setup>

import Layout from '../containers/Layout.vue';
import { reactive, toRefs } from 'vue'

const state = reactive({});
const props = defineProps({
    header: String
})


</script>

The thing that I am unsure about is how do I use the toRefs in this case? In the first case we are returning the variables so I understand the way we used ...toRefs(state) But now, how do I use it? Or is it not needed anymore? Thanks

CodePudding user response:

script setup implicitly translate variable definitions

const a = ...

to

return {
   a: ...
}

There is no substitute for return {...dynamicValue} in script setup, which is intended to suite common use cases only. This would require to combine it with script.

return {...toRefs(state)} serves no good purpose because the resulting refs aren't used in script block. Even if they are, they are usually defined as separate reactive values instead of state object:

const a = ref(...)
const b = reactive(...)

return { a, b }; // Not needed in script setup

If there is ever a need to handle these values as a single object, they could be combined together:

const a = ref(...)
const b = reactive(...)
const state = reactive({ a, b });

return { a, b }; // Not needed in script setup

This works it the same way for both script and script setup.

CodePudding user response:

If you want to access the values of the state reactive directly in script setup you can use Object destructuring like this :

import { reactive, toRefs } from "vue"

const state = reactive({ name: "admin", age: 20 })
const { name, age } = toRefs(state)

Then you can access your values directly in the template

<template>
    {{ name }}
</template>

However this is much less convenient to have to retype all of your properties

  • Related