简体   繁体   English

Vue - 如何在 VueJS 中正确使用计算属性?

[英]Vue - How to use computed properties correctly in VueJS?

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注意:每个结果值都会通过计算属性从 VueX 返回到组件

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

Is there a better way of doing this to improve readability?有没有更好的方法来提高可读性?

  • I think you could write getters separately in the Vuex file.我认为您可以在 Vuex 文件中单独编写 getter。
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.然后,您可以在 Vue 组件中使用 mapGetter。 It maps store getters to local computed properties:它将存储 getter 映射到本地计算属性:
import { mapGetters } from 'vuex';

export default {
  // ...
  computed: {
    // map `this.totalCoin` to `this.$store.getters.getTotalCoin`
    ...mapGetters({totalCoin: 'getTotalCoin', totalGem: 'getTotalGem'})
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM