Search code examples
vue.jsvisual-studio-codevuex

Vuejs: Using get and set property inside computed object in vuejs displays an error


Is declaring property (get() and set()) inside computed object is not allowed in vuejs?

The code works, however vscode shows tons of red color in the display, see screenshot for reference.

I'm not sure if vuejs or vscode triggers the error.

Farmer.js component

computed: {
        ...mapState("farmers", ["crud_step"]),
        normal_data(){ //this works
              return 'test';
        },
        step: { //this also works but this line causes an error display
            get() {
              return this.crud_step;
            },
            set(value) {
              return this.SET_CRUD_STEP(value);
            }
          },
      },

farmer.js store

const state = {[![enter image description here][1]][1]
  crud_step: 1,
  ...

};

const mutations = {
  SET_CRUD_STEP(state, value){
    state.crud_step = value;
  },
 ...
};

Note: eslint is disabled

Repo Link: https://github.com/juanPao/acms/blob/main/src/components/Farmers/FarmerCreate.vue enter image description here


Solution

  • Your computed doesn't look right. First off, you shouldn't return anything from the setter. It's an action. It's the getter which has to return a value.

    And you want the setter to commit the mutation. So your code could look like:

    computed: {
      ...mapState("farmers", ["crud_step"]),
      step: {
        get() {
          return this.crud_step;
        },
        set(value) {
          this.$store.commit('farmers/SET_CRUD_STEP', value);
        }
      }
    }
    

    ..., which makes it obvious you don't actually need two local props (crud_step and step), you can simply map the store's crud_step onto a local step:

    computed: {
      step: {
        get() {
          return this.$store.state.farmers.crud_step;
        },
        set(value) {
          this.$store.commit('farmers/SET_CRUD_STEP', value);
        }
      }
    }
    

    For consistency, I'd actually name the local property crud_step (which implies you have to also change it in the <template>). In the long run, sticking to consistent and clean naming patterns (whatever yours happen to be) will increase your efficiency in both coding and debugging.


    Since you haven't shown all the code in your component, I guessed you don't have a method called SET_CRUD_STEP which commits the mutation. Even if you do, it's unnecessary. You can simply commit from the setter. And if you used that method somewhere else in the component, replace it with this.step = someValue (which invokes the setter - that's what a setter is: a function which gets called when you assign something to that property).