Handling unexpected side effect in computed properties - VueJS

前端 未结 4 433
闹比i
闹比i 2021-01-07 23:12

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

相关标签:
4条回答
  • 2021-01-07 23:30

    ESLint is showing this error because you are mutating the original data in computed property. It is recommended that you should return new references or data from computed property.Follow this link for detailed explanation. https://github.com/vuejs/eslint-plugin-vue/blob/master/docs/rules/no-side-effects-in-computed-properties.md

    0 讨论(0)
  • 2021-01-07 23:30

    I would advice you to move allKeys array to computed and get rid of unnecessary tableHeaders and getKeys:

    <template>
        <select v-model="selected">
        <option v-for="key in allKeys" v-bind:key="key"> {{ key }}</option
        </select>
    </template>
    
    data(){
        return{
        selected: '',
        originalKeys: [],  //e.g. ["ALPHA_MIKE]
        getTranslation: {} //e.g. {"ALPHA_MIKE": "ALPHA MIKE"}
        }
    },
    computed: {
        allkeys() {
            return this.originalKeys.map(key => this.getTranslation[key])
        }
    }
    

    I'm not sure you need to assign this.selected = tableHeaders[0] since the first option will be chosen by default automatically.

    0 讨论(0)
  • 2021-01-07 23:49

    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
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-07 23:51

    As other answers mentioned this is because you are mutating the original data in a computed property. You should use a method to do this part of the job.

    methods:{
        changes(tableHeaders){
            this.selected = tableHeaders[0];
            this.allKeys = tableHeaders;
        }
    },
    computed:{
        getkeys(){
            // Your code...
            this.changes(tableHeaders);
        }
    },
    data: function(){
        return{
            // Your data...
        }
    }
    
    0 讨论(0)
提交回复
热议问题