Using script settings and reactive state vue 3 with toRefs
P粉387108772
P粉387108772 2023-08-26 15:38:41
0
2
478
<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粉387108772
P粉387108772

reply all(2)
P粉258083432

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

P粉593649715

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!