vuex当中state通过mapState映射到computed后,原来的计算属性要怎么写呢?

import {mapState} from 'vuex'

export default {
  data(){
      return {
          oldData: 0
      }
  }
  computed: mapState({
    count: state => state.count,
    newData(){
       return this.oldData + 1;
    }
  })
}

这样子写吗?

阅读 9k
2 个回答
import {mapState} from 'vuex'

export default {
  data() {
    return {        //你这里少写了
        oldData: 0
    }
  }
  computed: {
    ...mapState(["count"]),
    newData(){
       return this.oldData + 1;
    }
  }
}
新手上路,请多包涵
import { mapState } from 'vuex'

export default {
  data () {
    return {
      localCount: 1
    }
  },
  // mapState 辅助函数帮助我们生成计算属
  computed: mapState({
    // 箭头函数可使代码更简练
    count: state => state.count,
    // 传字符串参数 'count' 等同于 'state => state.count'
    countAlias: 'count',
    // 为了能使用 'this'获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
      return state.count + this.localCount
    },
    // 常规 computed, 没有使用 store的状态
    localCountAlias () {
      return this.localCount
    }
  })
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题