【问题标题】:possible to use computed functions as an attrubute's value in template? vue可以使用计算函数作为模板中的属性值吗? Vue
【发布时间】:2020-12-11 10:05:37
【问题描述】:

目前我正在从 youtube 学习 vue.js。有一些逻辑可以判断一个 html 元素是否应该具有哪个类。

在本教程中,将逻辑添加到 methods 中可以正常工作,但如果我将逻辑添加到 computed 中。我无法将其用作属性值

有解决方法吗?只是不知何故我觉得我应该将它添加到 computed 所以我尝试了它并且错误显示 [Vue warn]: Error in render: "TypeError: Cannot read property 'answerItemClass' of undefined" 我理解错误

我将它放入computed 可能是错误的,只是不知何故出现了这个问题,想知道如果将来我真的想放入computed 而不是methods,那么会有一个简单的解决方法吗?

下面的html示例

    <b-list-group-item
      v-for="(answer, index) in answers"
      v-html="answer"
      :key="index"
      :class="this.answerItemClass(index)"
      :disabled="answered"
      @click="selectAnswer(index)"
    >
    </b-list-group-item>

脚本,添加到 computed 而不是 methods

  computed: {
    answerItemClass(index) {
      let result = ''

      if (this.selectedIndex === index) result = 'selected';
      if ((this.answered) &&
        (this.correctAnswerIndex === index)
      ) result = 'correct';
      if ((this.answered) &&
        (this.selectedIndex === index) &&
        (this.correctAnswerIndex !== index)
      ) result = 'incorrect';

      return result;
    },
  }

提前感谢您的任何建议和建议。

【问题讨论】:

  • html模板中不需要this

标签: javascript vue.js methods computed-properties


【解决方案1】:

这是我个人的建议,提供更好的实现方式。

var Main = {
  data() {
    return {
      answers: [{
        answer: 'A',
        selected: false,
        correct: false
      }, {
        answer: 'B',
        selected: false,
        correct: true
      }, {
        answer: 'C',
        selected: false,
        correct: false
      }]
    };
  },
  methods: {
    selectAnswer(index) {
      this.answers = this.answers.map((v, i) => {
        if (i === index) {
          v.selected = !v.selected
        } else {
          v.selected = false
        }
        return v
      })
    }
  }
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
ul>li {
  cursor: pointer;
}

ul>li.selected {
  background-color: #eee;
}

ul>li.correct {
  background-color: green;
}

ul>li.incorrect {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id="app">
  <ul>
    <li v-for="(answer, index) in answers" :key="index" :class="{'selected': answer.selected, 'correct': answer.selected&&answer.correct,'incorrect': answer.selected&&!answer.correct}" @click="selectAnswer(index)">{{answer.answer}}</li>
  </ul>
</div>

将答案的状态放入数组的对象中,然后在遍历对象时通过取状态值来确定显示哪种样式。

【讨论】:

    【解决方案2】:

    如果你想传递这样的参数,我建议继续使用方法。计算方法被缓存并且只会随着依赖关系的变化而更新。方法将在每次调用时运行。虽然您可以将参数传递给计算值,但它通常用于在某处操作状态中的现有数据并返回它。

    Vue documentation here 对此进行了介绍。

    正如评论所述,从模板中删除任何对 this 的引用。

    【讨论】:

      猜你喜欢
      • 2020-08-02
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 2023-04-07
      • 2020-11-20
      • 1970-01-01
      • 2012-12-08
      相关资源
      最近更新 更多