VueXの最適化

1. #mapGetters補助関数
mapGetters補助関数は、ストア内のゲッターをローカルで計算された属性にマップするだけです。

//首先导入mapGetters
import {
    
     mapGetters } from 'vuex'

export default {
    
    
  // ...
  computed: {
    
    
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}

getterプロパティに別の名前を付ける場合は、オブジェクトフォームを使用します。

...mapGetters({
    
    
  // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})

2.
コンポーネントでアクション配布します。コンポーネントでthis。$ store.dispatch( 'xxx')を使用してアクションを配布するか、mapActionsヘルパー関数を使用してコンポーネントのメソッドをstore.dispatch呼び出しにマップします(挿入する必要があります)。最初にルートノードに保存します):

import {
    
     mapActions } from 'vuex'

export default {
    
    
  // ...
  methods: {
    
    
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
    
    
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}
state
export default {
    
    
  isFullScreen: false
}
mutations
export default {
    
    
  changeFullScreen (state, flag) {
    
    
      state.isFullScreen = flag
    }
}
export default new Vuex.Store({
    
    
  // state:用于保存全局共享的数据
  state: state,
  mutations: mutations,
  actions: actions,
  getters: getters

  /*
  很多代码放在一起会导致不容易后期维护
  state: {
    isFullScreen: false
  },
  // mutations:用于保存修改全局共享的数据的方法
  mutations: {
    changeFullScreen (state, flag) {
      state.isFullScreen = flag
    }
  },
  // actions 用于保存触发mutations中保存的方法的方法
  actions: {
    setFullScreen ({ commit }, flag) {
      commit('changeFullScreen', flag)
    }
  },
  getters: {
    isFullScreen (state) {
      return state.isFullScreen
    }
  }
  */
})

4.アクションの文字列を定数に変更します
ミューテーションタイプを作成します

export const SET_FULL_SCREEN = 'SET_FULL_SCREEN'

mutations.js

import {
    
     SET_FULL_SCREEN } from './mutations-type'
export default {
    
    
  /*
  changeFullScreen (state, flag) {
    state.isFullScreen = flag
  }
  */
  //想让常量作为方法名称 要加[]
  [SET_FULL_SCREEN] (state, flag) {
    
    
    state.isFullScreen = flag
  }
}

行動:

import {
    
     SET_FULL_SCREEN } from './mutations-type'
export default {
    
    
  /*
  setFullScreen ({ commit }, flag) {
    commit('changeFullScreen', flag)
  }
  */
  setFullScreen ({
    
     commit }, flag) {
    
    
    commit(SET_FULL_SCREEN, flag)
  }
}

おすすめ

転載: blog.csdn.net/mhblog/article/details/109229787