Home  >  Q&A  >  body text

Using script settings and reactive state vue 3 with toRefs

<p>I'm trying to use a script setup in my vue project. </p> <p>Before using the script settings, my script would look like this: </p> <pre class="brush:php;toolbar:false;"><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></pre> <p>Now I have this:</p> <pre class="brush:php;toolbar:false;"><script setup> import Layout from '../containers/Layout.vue'; import { reactive, toRefs } from 'vue' const state = reactive({}); const props = defineProps({ header: String }) </script></pre> <p>What I'm not sure about is how to use toRefs in this case? In the first case we return a variable, so I understand the way we use <code>...toRefs(state)</code> But now, how do I use it? Or no longer needed? Thank you</p>
P粉387108772P粉387108772444 days ago490

reply all(2)I'll reply

  • P粉258083432

    P粉2580834322023-08-27 13:34:51

    If you want to access the value of the state reaction directly in the script settings, you can use Object destructuring like this:

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

    You can then access your values ​​directly in the template

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

    However, all attributes must be re-entered, which is inconvenient

    reply
    0
  • P粉593649715

    P粉5936497152023-08-27 11:05:34

    Script settingsImplicit translation variable definition

    const a = ...

    to

    return {
       a: ...
    }

    return {...dynamicValue} in script settings is not replaceable and is intended only for common use cases. This requires combining it with script.

    return {...toRefs(state)} No benefit since the generated references are not used in the script block. Even if they are, they are usually defined as individual reactive values ​​rather than state objects:

    const a = ref(...)
    const b = reactive(...)
    
    return { a, b }; // Not needed in script setup

    If you need to handle these values ​​as a single object, you can combine them together:

    const a = ref(...)
    const b = reactive(...)
    const state = reactive({ a, b });
    
    return { a, b }; // Not needed in script setup

    It works the same way for scripts and script settings.

    reply
    0
  • Cancelreply