本章是对上一章 如何使用 vue + typescript 编写页面 ( vuex装饰器部分 )的补充 ,感谢 @慕容寒江
的提出建议vue
export default {
namespaced:true,
state:{
foo:""
},
getters:{
getFoo(state){ return state.foo}
},
mutations:{
setFooSync(state,payload){
state.foo = payload
}
},
actions:{
setFoo({commit},payload){
commot("getFoo",payload)
}
}
}
复制代码
vuex-module-decorators
import {
Module,
VuexModule,
Mutation,
Action,
MutationAction,
getModule } from 'vuex-module-decorators'
复制代码
export default class TestModule extends VuexModule { }
复制代码
VuexModule 提供了一些基本属性,包括namespaced
,state
,getters
,modules
,mutations
,actions
,context
其中context
则会在接下来的代码中使用到git
@Module
export default class TestModule extends VuexModule {
/* 这里表明的就是state里面的状态 */
inlineState = "";
/* 这里就是 getters 里面的内容*/
get named(){
return 1;
}
}
复制代码
module自己有几种能够配置的属性github
namespaced:boolean
启/停用 分模块stateFactory:boolean
状态工厂[我也不知道干什么的,有知道的能够留言]dynamic:boolean
在store建立以后,再添加到store中。 开启dynamic以后必须提供下面的属性name:string
指定模块名称store:Vuex.Store实体
提供初始的store动态模式为反向注入store。vuex
常规下是typescript
export default new Vuex.Store({
modules:{ TestModule }
})
复制代码
开启后为安全
// store.ts
export default new Vuex.Store({
modules:{ /* 其他的store */ }
})
复制代码
import store from './store'
@Module({
dynamic:true,
name: "TestModule",
store
})
export default class TestModule extends VuexModule { }
// 在须要引用的地方单独引用该store文件便可注入。
// 好处:灵活使用,仅仅在须要引入的地方才注入到store中去
// 缺点:须要单独引入文件
复制代码
@Module
export default class TestModule extends VuexModule {
inlineState = "";
@Mutation
setInlineStateSync(inlineState:string){
this.inlineState = inlineState;
}
}
复制代码
用法和@Emit
很类似async
@Module
export default class TestModule extends VuexModule {
@Action({ commit: 'setInlineStateSync' })
setInlineState(inlineState:string){
/*这里使用自动提交*/
return inlineState;
}
@Action
setInlineStateContext(inlineState:string){
/* 这里使用手动提交 */
this.context.commit("setInlineStateSync",inlineState)
}
}
复制代码
这个属性能够直接映射属性,函数
@Module
export default class TestModule extends VuexModule {
foo = "";
doo = "";
@MutationAction({mutate:["foo","doo"]/*提供须要映射的属性列表*/})
async setMutationAction(payload:{foo:string,doo:string} /* 传入的payload对象属性须要和mutate的名称一致*/){
/* 这里若是有返回,则必须返回一个Promise<{foo:string,doo:string}>类型*/
/* 可是在使用时,则有很奇葩的事情*/
/* 若是映射为Mutation [ @Mutation("TestModule/setMutationAction") ],则不会执行函数自己, 使用传入的值做为结果*/
/* 若是映射为Action [ @Action("TestModule/setMutationAction") ],会执行函数自己而且获得的返回值为结果 */
}
}
复制代码
@Module({ name : "tm" })
export default class TestModule extends VuexModule {
}
复制代码
常规,须要提供store,即:post
getModule(TestModule,this.$store).inlineState // "inlineState value"
复制代码
开启dynamic时,不须要提供store,由于module自己已经注入store。this
getModule(TestModule).inlineState // "inlineState value"
复制代码
更多内容参照vuex-module-decorators 或者 github:vuex-module-decorators