处理计算属性中的意外副作用 - VueJS [英] Handling unexpected side effect in computed properties - VueJS
问题描述
在下面的代码中,我尝试使用 getTranslation
对象来映射 originalKeys
数组中存在的值并将值推送到新数组 allKeys代码>.
In the following code, I'm trying to use the getTranslation
object to map values present in originalKeys
array and push the values in a new array allKeys
.
但是 ESLint 给了我这个错误,getkeys"计算属性中的意外副作用.
But ESLint is giving me this error, Unexpected side effect in "getkeys" computed property.
我尝试将 getkeys 函数转换为方法,但我认为每次都调用一个方法来完成翻译是没有意义的.我该如何解决这个问题?
I tried shifted the getkeys function to methods, but I think that it does not make sense to call a method everytime to get the translation done. How can I solve this issue?
<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
代替
As my above comment, you should not edit other data in computed
property, you should use watch
instead
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
}
}
}
这篇关于处理计算属性中的意外副作用 - VueJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!