问题
我需要在Vue模板中临时存储方法调用的结果。这在循环内部特别常见,在那里我不能很容易地使用计算属性。
<ul>
<li v-for="vehicleType in vehicleTypes" :key="vehicleType">
<h3>{{ vehicleType }}</h3>
<div v-if="getVehicleTypeData(vehicleType)">
{{ getVehicleTypeData(vehicleType).costPerMile }}<br>
{{ getVehicleTypeData(vehicleType).costPerHour }}<br>
</div>
</li>
</ul>
字符串
JavaScript程式码片段:
getVehicleTypeData: function(vehicleType){
let options = _.find(this.vehicleTypeOptions, (obj)=>{
return obj.vehicleType==vehicleType;
});
return options;
}
型
为了提高性能,我确实需要一个变量来存储方法调用结果。
Vue解决此问题的方法是什么?
8条答案
按热度按时间vulvrdjw1#
解决Vue当前缺点的一个快速方法是通过v-for和单个循环使用作用域。一个希望解释的例子:
字符串
上面的
<template>
元素可以做到这一点。您可以在一个临时的size-1对象数组中调用您的函数(someFunction
),将其分配给一个属性(isLocked
),然后将其分配给一个作用域变量(scope
)。现在您可以访问someFunction返回的任何内容,只要您愿意,而不会通过scope.isLocked
牺牲性能。00jrzges2#
在模板中的任何地方,你都可以用**:set=“VAART = 12”**来修改代码,神奇的是,VAART变量会被设置(但不会是被动的)。
在VUE 3上测试了这个魔术
new9mtju3#
你可以创建一个computed属性,将类型obj合并到vehiclesTypes数组中。
字符串
你可以做:
型
如果你遵循逻辑,我相信它会工作。虽然我不知道vehiclesTypes的值,所以上面的代码可能需要一些修改。
希望能帮到你。
xcitsw884#
一种选择是定义一个组件。您可以将需要“存储”的值作为 prop 传递给它,它可以以多种方式使用它。这是更像Vue的方法。
另一种选择是将函数调用 Package 在数组中,并使用
v-for
为其创建别名。这更像是一种黑客/懒惰的优化,但它并不脆弱,只是读起来很奇怪。个字符
lzfw57am5#
我从一些研究中找到了一个解决方案,我自己回答,但不确定是否有其他最好的解决方案。
JavaScript程式码片段:
字符串
模板片段:
型
zmeyuzjn6#
在目前的版本中,这是不可能的:(
在你的例子中,你可以用计算值来计算并使用它。
字符串
oyt4ldly7#
正如Fernando塞萨尔已经提到的,有一个未记录的特性
:set
,只是一个片段和一些链接字符串
https://github.com/vuejs/core/issues/1172#issuecomment-1035369827 www.example.com
f8rj6qna8#
这可能是一个可靠的策略:
字符串
可能还有一种方法可以在模板循环中定义变量。