使用 Vue 3 组合 API,如何返回属性 firstDigit 的计算值?计算属性中的关键字 this 是 undefined 但是当我将 this 排除在外时,我收到错误 fourDigits is not Defined。
<script setup>
import { computed, reactive } from 'vue'
const input = reactive({
fourDigits: Array(1,2,3,4),
firstDigit: computed(() => {
return this.fourDigits[0] <===== `this` is undefined but if I leave `this` out, then `fourDigits` is undefined.
})
</script>
<template>
<div>
<pre>
{{JSON.stringify(input.firstDigit, null, 2)}}
</pre>
</div>
</template>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果我需要使用状态属性为另一个状态属性赋值,我可以在 onMounted() 挂钩中执行此操作。像这样:
<script setup> import { computed, reactive } from 'vue' const input = reactive({ fourDigits: Array(1, 2, 3, 4), firstDigit: computed(() => { return 0; // just some default value }) }); onMounted(() => { input.firstDigit = input.fourDigits[0]; }) </script> <template> <div> <pre> {{ JSON.stringify(input.firstDigit, null, 2) }} </pre> </div> </template>检查它是否适合您。祝一切顺利!
this是组合 API 中的其他内容,请尝试使用:firstDigit: computed(() => { return input.fourDigits[0] })