decorators 参数_vuex-module-decorators简单使用

官方文档:https://championswimmer.in/vuex-module-decorators/

安装:

npm install vuex-module-decorators

store/index.ts

import Vue from 'vue';

import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({});

store/module/user.ts

import {VuexModule, Module, Mutation, Action, getModule} from 'vuex-module-decorators'

import store from '@/store'

// 参数一:module名称,开启命名空间后会以name为命名空间

// 参数二:是否使用动态加载,简而言之只有在用到当前的module才会加载,详细可以看vuex官网。本篇博客必须选择true,

// 这也是为什么index.ts一直不用修改的原因,如果设置为false会有很大的变动,如果您真的需要这么做,可以自己研究一下,

// 或者私信我。

// 参数三:是否开启命名空间,如果你的模块很多,强烈建议开启

// 参数四:挂载的store目标

@Module({name: "user", dynamic:true, namespaced: true,store})

export default class User extends VuexModule{

public name:string = '';

public message: string = '未知';

get getMessage(){

return `当前时间${new Date()}:${this.message}`;

}

@Mutation

private SET_NAME(name: string){

this.name = name;

}

@Mutation

private SET_MESSAGE(message: string){

this.message = message

}

@Action

public getUser(name: string){

if (name === "admin") {

this.SET_NAME("admin");

this.SET_MESSAGE("测试成功");

} else {

this.SET_MESSAGE("测试失败");

}

}

}

export const UserModule = getModule(User);

参考资料:vuex的模块动态注册

上面的代码和下面是类似的

const UserModule = {

state: {

name: '',

message: ''

},

getters: {

getMessage: state => `当前时间${new Date()}:${state.user.message}`

},

mutations: {

SET_NAME: (state, name) => {

state.name = name

},

SET_MESSAGE: (state, message) => {

state.message = message

}

},

actions: {

getUser({commit}, name){

if (name === "admin") {

commit("SET_NAME", "admin");

commit("SET_MESSAGE", "测试成功");

} else {

commit("SET_MESSAGE", "测试失败");

}

}

},

}

使用

User.vue

{{$store.state.user.message}}

在script中使用state的内容或者action的方法,你都可以直接用模块调取,但是在html模板中只能用$store的方式获取

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值