简介
脚手架vue-cli2.x
搭建的项目中使用vuex
参考:Vue常用插件:vuex
这里介绍Typescript
的写法
store定义
- 在
src/store/
目录下新建state.ts
文件
export interface State {
deviceId: string,
sessionId: string,
user: any,
showLogin: boolean
}
const state: State = {
deviceId: '123',
sessionId: '',
user: {},
showLogin: false
}
export default state
- 在
src/store/
目录下新建getters.ts
文件
import { GetterTree } from 'vuex'
import { State } from './state'
const getters: GetterTree<State, any> = {
// deviceId(state: State): string {
// return state.deviceId
// },
// sessionId(state: State): string {
// return state.sessionId
// },
// user(state: State): void {
// return state.user
// },
deviceId: (state: State) => state.deviceId,
sessionId: (state: State) => state.sessionId,
user: (state: State) => state.user
}
export default getters
- 在
src/store/
目录下新建mutations.ts
文件
import { MutationTree } from 'vuex'
import { State } from './state'
const mutations: MutationTree<any> = {
setDeviceId(state: State, id: string): void {
state.deviceId = id
},
setUserIsLogin(state: State, flag: boolean): void {
state.user.isLogin = flag
},
showLogin(state: State, flag: boolean): void {
state.showLogin = flag
}
}
export default mutations
- 在
src/store/
目录下新建actions.ts
文件
import { ActionTree, Commit } from 'vuex'
import { State } from './state'
const actions: ActionTree<State, any> = {
actionTest({ commit, state }, data: any[]) {
// ...
// console.log(commit, state)
}
}
export default actions
- 在
src/store/
目录下新建index.ts
文件
import Vue from 'vue';
import Vuex from 'vuex';
import state from './state'
import getters from './getters'
import mutations from './mutations'
import actions from './actions'
// import createPersistedState from 'vuex-persistedstate'
import createLogger from 'vuex/dist/logger'
Vue.use(Vuex);
// const plugins: Array<any> = [createPersistedState()]
const plugins: any[] = []
if (process.env.NODE_ENV !== 'production') {
plugins.push(createLogger())
}
const store = new Vuex.Store({
state,
getters,
mutations,
actions,
plugins
})
export default store
vue组件中使用
// 使用 vuex-class
import { Component, Prop, Vue } from 'vue-property-decorator';
import { State, Getter, Mutation } from 'vuex-class';
@Component
export default class Test extends Vue {
@State private sessionId: string;
@Getter private deviceId: string
// @Mutation('setDeviceId') private setDeviceId!: any;
@Mutation private setDeviceId: any;
private deviceIdChange() {
this.setDeviceId('456')
}
}
发表评论