在下面的代码中,我试图使用getTranslation对象映射originalKeys数组中存在的值,并将值推入新的数组allKeys中。

但是ESLint给我这个错误,Unexpected side effect in "getkeys" computed property.
我尝试将getkeys函数转换为方法,但是我认为每次都调用一个方法来完成翻译是没有意义的。
我该如何解决这个问题?

<template>
    <select v-model="selected">
    <option v-for="key in getkeys" v-bind:key="key"> {{ key }}</option
    </select>
</template>

data(){
    return{
    selected: '',
    allKeys: [],
    originalKeys: [],  //e.g. ["ALPHA_MIKE]
    getTranslation: {} //e.g. {"ALPHA_MIKE": "ALPHA MIKE"}
    }
},
computed: {
    getkeys(){
        let tableHeaders = [];
        for( var i=0; i<this.originalKeys.length; i++){
            let translation = this.getTranslation[this.originalKeys[i]];
            tableHeaders.push(translation);
        }
        this.selected = tableHeaders[0]; //unexpected side effect here
        this.allKeys = tableHeaders; //unexpected side effect here.
        return this.allKeys;
    }
}

最佳答案

正如我上面的评论,您不应在computed属性中编辑其他数据,而应改用watch

computed: {
    getkeys(){
        let tableHeaders = [];
        for( var i=0; i<this.originalKeys.length; i++){
            let translation = this.getTranslation[this.originalKeys[i]];
            tableHeaders.push(translation);
        }
        return tableHeaders;
    }
},
watch: {
  getkeys: {
    deep: true,
    handler: function (newVal) {
      this.selected = newVal[0]
      this.allKeys = newVal
    }
  }
}

关于javascript - 处理计算属性中的意外副作用-VueJS,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53757107/

10-12 15:44