本文介绍了如何在 Vue.js 模板中定义临时变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我当前的模板:

<a-droppable v-for="n in curSize" :key="n - 1" :style="{width: `${99.99 / rowLenMap[orderList[n - 1]]}%`, order: orderList[n - 1]}">
  <a-draggable :class="{thin: rowLenMap[orderList[n - 1]] > 10}">
    <some-inner-element>{{rowLenMap[orderList[n - 1]]}}</some-inner-element>
  </a-draggable>
</a-droppable>

问题是我要多次写rowLenMap[orderList[n - 1]],恐怕vue.js引擎也会多次计算.

The problem is that i have to write rowLenMap[orderList[n - 1]] multiple times, and i'm afraid vue.js engine will also calculate it multiple times.

我想要的是这样的:

<a-droppable v-for="n in curSize" :key="n - 1" v-define="rowLenMap[orderList[n - 1]] as rowLen" :style="{width: `${99.99 / rowLen}%`, order: orderList[n - 1]}">
  <a-draggable :class="{thin: rowLen > 10}">
    <some-inner-element>{{rowLen}}</some-inner-element>
  </a-draggable>
</a-droppable>

我认为在技术上实现并不难,因为它可以通过使用诸如v-for="rowLen in [rowLenMap[orderList[n - 1]]]"之类的东西来笨拙地解决.那么有没有简洁的官方解决方案?

I think it's not difficult to implement technically because it can be clumsily solved by using something like v-for="rowLen in [rowLenMap[orderList[n - 1]]]". So is there any concise and official solution?

推荐答案

curSize 是一个数组.您的临时值包含一个相应的隐含数组 sizedOrderList = curSize.map(n => orderList[n-1]).如果你把它定义为一个计算,你的 HTML 就变成了

curSize is an array. Your temporary values comprise a corresponding implied array sizedOrderList = curSize.map(n => orderList[n-1]). If you define that as a computed, your HTML becomes

<a-droppable v-for="n, index in sizedOrderList" :key="curSize[index]" :style="{width: `${99.99 / rowLenMap[n]}%`, order: n}">
  <a-draggable :class="{thin: rowLenMap[n] > 10}">
    <some-inner-element>{{rowLenMap[n]}}</some-inner-element>
  </a-draggable>
</a-droppable>

这篇关于如何在 Vue.js 模板中定义临时变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 12:26