【问题标题】:error Unexpected side effect in "allOptions" computed property vue/no-side-effects-in-computed-properties错误“allOptions”计算属性vue / no-side-effects-in-computed-properties中的意外副作用
【发布时间】:2021-06-20 02:49:25
【问题描述】:

我试图在 Vue js 的 computed 区域中的数组中找到答案的索引,但我收到一个错误,表明发生了一些意外的副作用

代码:-

<script>
import _ from "lodash";

export default {
  name: "QuestionBottom",
  props: {
    currentQuestion: Object,
    nextQuestion: Function,
    increment: Function,
  },
  data() {
    return {
      selectedIndex: null,
      correctIndex: null,
    };
  },
  // watch changes to the props
  watch: {
    currentQuestion() {
      this.selectedIndex = null;
    },
  },

  computed: {
    allOptions() {
      let allOptions = [
        ...this.currentQuestion.incorrect_answers,
        this.currentQuestion.correct_answer,
      ];

      console.log("array that is not shuffled is ", allOptions);
      allOptions = _.shuffle(allOptions);
      console.log("shuffled array is", allOptions);
      console.log("Corect ans is ", this.currentQuestion.correct_answer);

      // here is the error occurring
      this.correctIndex = allOptions.indexOf(
        this.currentQuestion.correct_answer
      );
      return allOptions;
    },
  },

  methods: {
    selectedAns(index) {
      this.selectedIndex = index;
      console.log("Selected answer index", this.selectedIndex);
    },
    submitAnswer() {
      let isCorrect = false;
      if (this.selectedIndex === this.correctIndex) {
        isCorrect = true;
      }

      this.increment(isCorrect);
    },
  },

  mounted() {
    // console.log(this.currentQuestion);
  },
};
</script>

我是 Vue.js 的新手。我不知道在我的数组的计算区域中发生这种意外行为的原因是什么。

【问题讨论】:

    标签: javascript vue.js vue-component lodash


    【解决方案1】:

    Vue 不喜欢在计算属性 (allOptions) 中更改数据变量 (correctIndex)。我会把那部分放在一个被监视的方法中。 https://vuejs.org/v2/guide/computed.html#Watchers

    computed: {
        allOptions() {
          let allOptions = [
            ...this.currentQuestion.incorrect_answers,
            this.currentQuestion.correct_answer,
          ];
    
          console.log("array that is not shuffled is ", allOptions);
          allOptions = _.shuffle(allOptions);
          console.log("shuffled array is", allOptions);
          console.log("Corect ans is ", this.currentQuestion.correct_answer);
          return allOptions;
        },
    
        watch: {
            allOptions() {
                this.correctIndex = allOptions.indexOf(this.currentQuestion.correct_answer);
            }
        }
    

    这样allOptions 会保持计算状态,并且只会做它的事情(仅此而已) - 但会被监视。每次更改时,correctIndex 都会相应更新。

    【讨论】:

      猜你喜欢
      • 2021-09-02
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2020-09-20
      • 2019-10-03
      • 2019-06-11
      • 2020-12-01
      相关资源
      最近更新 更多