首頁  >  問答  >  主體

Vue 3 組合 api - 計算屬性傳回未定義

使用 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粉662089521P粉662089521354 天前579

全部回覆(2)我來回復

  • P粉557957970

    P粉5579579702023-11-01 14:49:47

    如果我需要使用狀態屬性為另一個狀態屬性賦值,我可以在 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>
    

    檢查它是否適合您。祝一切順利!

    回覆
    0
  • P粉611456309

    P粉6114563092023-11-01 14:49:14

    this 是組合 API 中的其他內容,請嘗試使用:

    firstDigit: computed(() => {
      return input.fourDigits[0] 
    })

    回覆
    0
  • 取消回覆