V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
gap
V2EX  ›  Vue.js

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

  •  
  •   gap · Apr 12, 2017 · 9787 views
    This topic created in 3303 days ago, the information mentioned may be changed or developed.

    之前项目用的是 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 replies    2017-04-12 23:35:36 +08:00
    445141126
        1
    445141126  
       Apr 12, 2017
    mapState, mapGetters 放在 computed, mapActions, mapMutations 放在 methods
    gap
        2
    gap  
    OP
       Apr 12, 2017
    @445141126


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

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

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

    mounted() {
    // 原本这个赋值逻辑应该是在 data() 属性中的,但 data() 属性赋值的时候 this.currentArea 还是 undefined
    this.$data.selectedArea = this.currentArea
    }
    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1326 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 23:46 · PVG 07:46 · LAX 16:46 · JFK 19:46
    ♥ Do have faith in what you're doing.