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
statereaction 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
Script settingsImplicit translation variable definitionto
return { a: ... }return {...dynamicValue}in script settingsis 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 thanstateobjects:const a = ref(...) const b = reactive(...) return { a, b }; // Not needed in script setupIf 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 setupIt works the same way for
scriptsandscript settings.