[Vuejs]-Possible to use computed functions as an attrubute's value in template? vue

0👍

If you want to pass an argument like that, I recommend continuing to use methods. Computed methods are cached and will only update with dependency changes. Methods will run every time they are called. While you could pass an argument into a computed, it’s typically done for manipulating existing data in state somewhere and returning it.

This is covered in the Vue documentation here.

And as the comment stated, remove any references of this from the template.

0👍

This is my personal suggestion to provide a better way to achieve.

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>

Put the state of the answer in the object of the array, and then determine which style to display by taking the state value when traversing the object.

Leave a comment