當我嘗試從函式中獲取模板上的值時,我遇到了很多重復的情況,該函式從模板中接收引數(例如 v-for 的索引)并回傳列印在模板上的結果,問題是我需要執行兩次此操作,并且由于已經計算了該值,因此我看不到呼叫兩次相同的函式來獲取模板上的值的意義,但是如何和在哪里存盤這個值以供重用,我知道計算會快取該值,但據我所知,計算不會使用引數,這就是我需要一個函式的原因。
例子:
<template v-for="attr in el.attrs">
<div v-for="(step, i) in steps" :title="getVal(i, attr.key))">
{{ getVal(i, attr.key) ? '◇' : '-' }}
</div>
</template>
我嘗試通過將 getVal 的值存盤在 ref 中,但隨后它發出警告“組件中超出遞回更新”并且運行速度非常慢。
任何解決方法/解決方案/想法?謝謝!
uj5u.com熱心網友回復:
有2種方法可以解決這個問題:
進行計算,它使用一些額外的計算屬性擴展原始陣列的專案。計算的屬性被快取,并且僅在其依賴項更新時重新計算。這種方法也會讓你的模板更干凈
const extendedSteps = computed(() => {
return steps.map((step, stepIndex) => {
const title = getTitle(stepIndex)
return {
...step,
title,
symbol: title ? '◇' : '-'
}
})
})
<div v-for="step in extendedSteps" :title="step.title">
{{ step.symbol }}
</div>
另一種選擇是制作一個代表串列中單個專案的組件。在那里您可以創建一個常規計算屬性,它將分別計算和快取每個專案所需的任何內容
// parent template
<Step v-for="step in steps" :step="step" />
// Step.vue script
const props = defineProps(['step'])
const title = computed(() => getTitle(props.step))
const symbol = computed(() => title ? '◇' : '-')
// Step.vue template
<div>
{{ title }} {{ symbol }}
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/524145.html
