如何在 vue 模板中定义变量?

Xin*_*g L 6 javascript vue.js vue-component

问题

我需要在 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>
Run Code Online (Sandbox Code Playgroud)

Javascript 片段:

getVehicleTypeData: function(vehicleType){
    let options = _.find(this.vehicleTypeOptions, (obj)=>{
      return obj.vehicleType==vehicleType;
    });

    return options;
}
Run Code Online (Sandbox Code Playgroud)

为了提高性能,我真的需要一个变量来存储方法调用结果。

Vue 有什么方法可以解决这个问题?

unt*_*ill 11

解决 Vue 当前缺点的一种快速方法是通过 v-for 和单个循环使用范围。一个希望解释的例子:

<v-list>
  <v-list-tile v-for="(module, idx) in modules">
    <template v-for="scope in [{ isLocked: someFunction(module)}]">
      <!-- any markup -->
      <v-list-tile-action v-if="scope.isLocked">
        <v-icon color="amber">lock</v-icon>
      </v-list-tile-action>
    </template>
  </v-list-tile>
</v-list>
Run Code Online (Sandbox Code Playgroud)

<template>上面的元素可以解决问题。您someFunction在一个临时大小为 1 的对象数组中调用您的函数 ( ),将其分配给一个属性 ( isLocked),该属性又分配给一个作用域变量 ( scope)。您现在可以通过scope.isLocked.


小智 6

在模板中的任何位置,您都可以使用:set="VAART = 12"破解代码,并且神奇地会设置 VAART 变量(但不会反应)

在 VUE 3 上测试了这个魔术