在Vue JS上的v-for循环中设置变量

rya*_*gus 4 vuejs2 v-for

我在SPA上有一个带vue.js的v-for循环,我想知道在开始时设置变量是否可行,然后每次需要时都打印它,因为现在我每次需要时都调用一个方法打印变量.

这是JSON数据.

{
"likes": ["famiglia", "ridere", "caffè", "cioccolato", "tres leches", "ballare", "cinema"],
"dislikes":["tristezze", "abuso su animali", "ingiustizie", "bugie"]
Run Code Online (Sandbox Code Playgroud)

}

然后我在循环中使用它:

<template>
<div class="c-interests__item" v-for="(value, key) in interests" :key="key" :data-key="key" :data-is="getEmotion(key)" >

// NOTE: I need to use the variable like this in different places, and I find myself calling getEmotion(key) everythime, is this the way to go on Vue? or there is another way to set a var and just call it where we need it?

<div :class="['c-card__frontTopBox', 'c-card__frontTopBox--' + getEmotion(key)]" ...
<svgicon :icon="getEmotion(key) ...

</div>
</template>

<script>
import interests from '../assets/json/interests.json'
... More imports

let emotion = ''

export default {
  name: 'CInfographicsInterests',
  components: {
    JSubtitle, svgicon
  },
  data () {
    return {
      interests,
      emotion
    }
  },
  methods: {
    getEmotion (key) {
      let emotion = (key === 0) ? 'happy' : 'sad'
      return emotion
    }
  }
}
</script>

// Not relevanty to the question
<style lang='scss'>
.c-interests{...}
</style>
Run Code Online (Sandbox Code Playgroud)
  1. 我尝试添加一个道具,如:testy ="getEmotion(key)"然后{testy}没有运气......

  2. 我试着直接打印{emotion}但它不起作用

所以,无论如何都要完成这个或者我应该每次都坚持调用这个方法吗?

在此先感谢您的帮助.

Dan*_*iel 6

是的,所以在模板中包含非用户指导的动作(如onClicks)并不是一个好主意.在性能,内部循环方面,它尤其糟糕.

因此,您可以使用计算变量来存储状态,而不是使用方法

computed: {
  emotions() {
    return this.interests.map((index, key) => key === 0 ? 'happy' : 'sad');
  }
}
Run Code Online (Sandbox Code Playgroud)

这将创建一个返回所需数据的数组,以便您可以使用

__CODE__

这将减少重新绘制项目的次数.

  • 我很好奇,为什么要使用data-is和data-key?好像您在这里使用另一个库。如果是这种情况,请考虑坚持一个,因为这可能会引起一些冲突。 (2认同)