使用脚本设置和响应式状态 vue 3 与 toRefs
<p>我正在尝试在我的 vue 项目中使用脚本设置。</p>
<p>在使用脚本设置之前,我的脚本将是这样的:</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>现在我有这样的:</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>我不确定的是在这种情况下如何使用 toRefs?在第一种情况下,我们返回变量,因此我了解我们使用 <code>...toRefs(state)</code> 的方式
但现在,我该如何使用它呢?或者不再需要了?
谢谢</p>
如果您想直接在脚本设置中访问
state反应的值,您可以使用 对象解构如下所示:import { reactive, toRefs } from "vue" const state = reactive({ name: "admin", age: 20 }) const { name, age } = toRefs(state)然后您可以直接在模板中访问您的值
<template> {{ name }} </template>但是,必须重新输入所有属性,这不太方便
脚本设置隐式翻译变量定义至
return { a: ... }脚本设置中的return {...dynamicValue}是不可替代的,它仅适用于常见用例。这需要将其与脚本结合起来。return {...toRefs(state)}没有什么好处,因为脚本块中不使用生成的引用。即使它们是,它们通常也被定义为单独的反应值而不是state对象:const a = ref(...) const b = reactive(...) return { a, b }; // Not needed in script setup如果需要将这些值作为单个对象处理,可以将它们组合在一起:
const a = ref(...) const b = reactive(...) const state = reactive({ a, b }); return { a, b }; // Not needed in script setup对于
脚本和脚本设置来说,其工作方式是相同的。