V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
gap
V2EX  ›  Vue.js

去掉 Vue 自定义组件中的 vuex 属性, mapGetter 回来的 state 内容应该放到 data 里面还是 computed 里面呢?

  •  
  •   gap · 2017-04-12 16:00:16 +08:00 · 9229 次点击
    这是一个创建于 2563 天前的主题,其中的信息可能已经有所发展或是发生改变。

    之前项目用的是 vuex 0.x 版本,每个自定义组件中的 state 都是在组建 vuex 属性里面返回的,类似:

      vuex: {
        getters: {
          currentPeriod: state => state.currentPeriod
        },
        actions: {
          changeCurrentPeriod
        }
      }
    

    升级 vuex 2.x 后,看教程的 sample 都没有用 vuex 属性了,直接在 component 的 computed 的方法中,用 mapGetter 来取 state 中的值,类似:

    computed: mapGetter(['currentPeriod'])
    

    我的问题是,拿到所有情况下都将 mapGetter 的 state 内容放在 computed 对象上?data() { return {} } 好像不支持 mapGetter 。

    另外,有用了 vuex 2.x 后,自定义组件还保留了 vuex 属性的例子吗?看了一圈 github 的些 vue + vuex 2 项目都用的 mapGetters 和 mapSetters 。

    4 条回复    2017-04-12 23:35:36 +08:00
    445141126
        1
    445141126  
       2017-04-12 16:08:16 +08:00
    mapState, mapGetters 放在 computed, mapActions, mapMutations 放在 methods
    gap
        2
    gap  
    OP
       2017-04-12 16:14:46 +08:00
    @445141126


    我现在遇到个问题, data 中用到的 state 返回了 undefined ,貌似是 computed 属性返回慢了一步?

    ```js
    data() {
    return {
    selectedPeriod: this.currentPeriod // view 中访问 this.selectedPeriod.from 报错
    }
    },
    computed: mapGetter(['currentPeriod'])
    ```
    445141126
        3
    445141126  
       2017-04-12 17:07:43 +08:00   ❤️ 1
    对, 你可以在 created 里面再给 data 赋值
    gap
        4
    gap  
    OP
       2017-04-12 23:35:36 +08:00
    @445141126 您的意思是这样吗?感觉好丑...

    ```
    computed: {
    ...mapState({
    currentArea: 'currentArea'
    })
    },

    mounted() {
    // 原本这个赋值逻辑应该是在 data() 属性中的,但 data() 属性赋值的时候 this.currentArea 还是 undefined
    this.$data.selectedArea = this.currentArea
    }
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   946 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:30 · PVG 05:30 · LAX 14:30 · JFK 17:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.