Using script settings and reactive state vue 3 with toRefs
P粉387108772
2023-08-26 15:38:41
<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>
If you want to access the value of the
state
reaction directly in the script settings, you can use Object destructuring like this:You can then access your values directly in the template
However, all attributes must be re-entered, which is inconvenient
Script settings
Implicit translation variable definitionto
return {...dynamicValue}
in script settings
is not replaceable and is intended only for common use cases. This requires combining it withscript
.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 thanstate
objects:If you need to handle these values as a single object, you can combine them together:
It works the same way for
scripts
andscript settings
.