Computed 如何在 Vue 3 脚本设置中工作?

How does Computed work in Vue 3 script setup?

我正在努力让 computed<script setup> 中工作:

<template>
  <div>
    <p>{{ whatever.get() }}</p>
  </div>
</template>


<script setup>
import {computed} from "vue";

const whatever = computed({
    get() {
        console.log('check')
        return 'check?';
    }
})
</script>

console.log() 通过了,但是 return 语句似乎抛出错误:

check
Vue warn]: Unhandled error during execution of render function 
  at <Cms>
Uncaught TypeError: $setup.whatever.get is not a function
at Proxy.render (app.js?id=d9e007128724c77a8d69ec76c6c081a0:39550:266)
at renderComponentRoot (app.js?id=d9e007128724c77a8d69ec76c6c081a0:25902:44)
at ReactiveEffect.componentUpdateFn [as fn] (app.js?id=d9e007128724c77a8d69ec76c6c081a0:30019:57)
at ReactiveEffect.run (app.js?id=d9e007128724c77a8d69ec76c6c081a0:23830:29)
at setupRenderEffect (app.js?id=d9e007128724c77a8d69ec76c6c081a0:30145:9)
at mountComponent (app.js?id=d9e007128724c77a8d69ec76c6c081a0:29928:9)
at processComponent (app.js?id=d9e007128724c77a8d69ec76c6c081a0:29886:17)
at patch (app.js?id=d9e007128724c77a8d69ec76c6c081a0:29487:21)
at render (app.js?id=d9e007128724c77a8d69ec76c6c081a0:30630:13)
at mount (app.js?id=d9e007128724c77a8d69ec76c6c081a0:28882:25)

我做错了什么?

Computed properties appear as fields. 不管你是传入一个函数(如 computed(() => /*...*/))还是一个带有 get() 方法的对象(如果你不这样做,这里是等价的) t 提供 set() 方法)。

您的模板应该只使用您计算的 属性 的名称,这里是 whatever

<template>
  <div>
    <p>{{ whatever }}</p>
  </div>
</template>

<template>:

Getter:

  • {{ myVal }}
  • <p v-text="myVal" />

Getter 和 setter:

  • <input v-model="myVal">

重要:不要不要使用myVal.get()myVal.set(value)!使用:

  • 得到:myVal
  • 设置(赋值):myVal = value

<script setup>:

Getter:

const someReactiveRef = ref(null)

const myVal = computed(() => someReactiveRef.value);

Getter & setter:

const someReactiveRef = ref(null)

const myVal = computed({
  get() { return someReactiveRef.value },
  set(val) { someReactiveRef.value = val; }
});
// myVal can now be used in `v-model`

当反应性引用来自 reactive() 对象的 属性 时,您不需要 setter 或 [=85= 中的 .value ].示例:

const store = reactive({
  someProp: null
})

const myVal = computed({
  get() { return store.someProp },
  set(val) { store.someProp = val; }
});

重要提示:

  • 当将 non-reactive 引用传递给 computed 时,Vue 会警告您(不需要计算包装器)。
  • 当向它传递一个包含循环依赖(例如:组件实例)的 ref 时,Vue 将再次警告您并建议您使用 shallowRefmarkRaw.