2

I have some computed properties with different values, may I ask anyway to organize my data?

computed: {
  totalCoin() {
    const state = this.$store.state.ApiState.totalCoin
    let val
    if (state === 0) {
      val = 0
    } else if (state === null) {
      val = undefined
    } else {
      val = state
    }
   return val
  },
  totalGem() {
    const state = this.$store.state.ApiState.totalGem
    let val
    if (state === 0) {
      val = 0
    } else if (state === null) {
      val = undefined
    } else {
      val = state
    }
   return val
  }
  repeatedly...
}

Note: Every results value will return from VueX to a component by computed properties

getToken() {
  return this.$store.state.userToken
}

Is there a better way of doing this to improve readability?

0

1 Answer 1

1
  • I think you could write getters separately in the Vuex file.
const getters = {
    getTotalCoin(state){
        return state.totalCoin == null? undefined : state.totalCoin;
    },
    getTotalGem(state){
        return state.totalGem== null? undefined : state.totalGem;
    }
}
  • Then, you can use mapGetter in your Vue component. It maps store getters to local computed properties:
import { mapGetters } from 'vuex';

export default {
  // ...
  computed: {
    // map `this.totalCoin` to `this.$store.getters.getTotalCoin`
    ...mapGetters({totalCoin: 'getTotalCoin', totalGem: 'getTotalGem'})
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.