Vue 3 组合 api - 计算属性返回未定义
P粉662089521
P粉662089521 2023-10-31 19:00:10
0
2
531

使用 Vue 3 组合 API,如何返回属性 firstDigit 的计算值?计算属性中的关键字 thisundefined 但是当我将 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>


P粉662089521
P粉662089521

全部回复(2)
P粉557957970

如果我需要使用状态属性为另一个状态属性赋值,我可以在 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>

检查它是否适合您。祝一切顺利!

P粉611456309

this 是组合 API 中的其他内容,请尝试使用:

firstDigit: computed(() => {
  return input.fourDigits[0] 
})
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!