Vuexデータ共有プロジェクトの重要な部分であり、この記事では、プロジェクト内の個人的な使用Vuexの使用をまとめました。
- プロジェクトディレクトリのsrc /ストアの設定
単一の文書管理に抽象化のアクション、ゲッター、変異、状態を、。より簡潔な変異を見るためには、変異型はまた、一元管理を分割します。
├── store
├── index.js # 我们组装模块并导出 store 的地方
├── state.js # 根级别的 states
├── getters.js # 根级别的 getters
├── actions.js # 根级别的 action
├── mutations.js # 根级别的 mutation
└── mutation-types.js # mutation类型
- index.js
import Vue from 'vue'
import Vuex from 'vuex'
import * as mutations from './mutations'
import * as actions from './actions'
import state from './state'
import createLooger from 'vuex/dist/logger' // 在没有装vue-devtools的情况下可以使用,在控制台会打印出state前后状态变化
Vue.use(Vuex)
const debug = process.env.NODE_ENV === 'production'
export default new Vuex.store({
state,
mutations,
actions,
getters,
strict: debug, // 开发环境下开启严格模式,任何不是由mutation引起更改state的操作都会抛出错误,确保在发布环境下关闭严格模式,以避免性能损失。
plungins: debug ? [createLogger()] : [] // 开发环境下开启
})
- state.js
例えば、以下のようにグローバルに共有データを:
export default state = {
userName: '',
stationList: [],
station: {}
}
- getters.js
Vuexストアはゲッターの定義は、属性ストアを計算することが考えられることができます。値が変化した場合には再計算されます。
その最初のパラメータとして受信状態ゲッター。
export const userName = state => state.userName
export const stationList = state => state.stationList
export const station = state => state.station
Vuex応答状態から使用中のデータは、属性ストアインスタンスから計算されたデータを使用して読み取ることができるように、記憶されています。
import { mapGetters } from 'vuex
computed: {
...mapGetters([
name: 'userName',
'stationList',
'station'
])
}
- actions.js
アクションが直接状態を変更せずに、突然変異のために提出されました。
import * as types from './mutation-types'
export const selectStation = function({ commit, state }, param) {
if(state.stationList.length === 0) {
commit(types.SELECT_STATION, param)
}
}
あなたは、アクションの使用方法を使用する必要があります。
import { mapActions } from 'vuex'
methods: {
...mapActions([
'selectStation'
]),
_changeStation(station) {
this.selectStation(station)
}
}
- mutations.js
import * as types from './mutation-types'
export mutations = {
[types.SELECT_STATION](state, param) {
state.station = param
}
}
- 変異types.js
フラックスのさまざまなインプリメンテーションに一定の置換変異のイベントタイプを使用しては非常に一般的なパターンです。これは、役割を果たしているようなツールのリンターを可能にするが、あなたのコード内の別のファイルにこれらの定数は、変異協力者が一目で全体アプリを含まことができます:
export const SELECT_STATION = 'SELECT_STATION'
https://github.com/Gesj-yean/vue-demo-collection文書の使用より優れたプラグイン。学生はどうもありがとうございましたことができ、私の一番上のブログを見て時間を持っています。