vue-property-decorator
npm包使用下面三条命令行进行包的安装
npm install vuex --save
npm install vuex-module-decorators -s
npm install vuex-class -s
首先在 src 文件夹中创建一个名为 vuex 的文件夹,并在其中创建名为 store.ts 的文件,
store.ts 的内容如下:
import Vue from 'vue';
import Vuex from 'vuex';
import { VuexModule, Module, Mutation, Action } from 'vuex-module-decorators';
Vue.use(Vuex);
@Module
class VuexStore extends VuexModule {
public foo: number = 111;
get axles() {
return this.foo / 2;
}
@Action({ commit: 'MutationMeth' })
public ActionMeth() {
return 8;
}
@Mutation
public MutationMeth() {
++this.foo; // 改变 this.foo
}
}
export default new Vuex.Store(VuexStore);
随后在 main.ts 中引入刚刚创建的 store.ts 文件。
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import store from '@/vuex/store';
Vue.config.productionTip = false;
Vue.use(ElementUI); // 引入所有ElementUI组件
new Vue({
router,
store,
render: (h) => h(App),
}).$mount('#app');
<template>
<div class="home">
<div>通过 Vuex 获得的值:{{ stateFoo }}------{{ axles }}div>
<el-button type="primary" @click="ActionMeth">经过Actionel-button>
<el-button type="primary" @click="MutationMeth">不经过Actionel-button>
div>
template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { State, Action, Mutation, Getter } from 'vuex-class';
@Component
export default class Home extends Vue {
@State private foo!: number; // 同名
@State('foo') private stateFoo!: number; // 重命名
@Getter private axles!: number;
@Action('ActionMeth')
private ActionMeth!: () => void;
@Mutation('MutationMeth')
private MutationMeth!: () => void;
}
script>
在 @click=“ActionMeth” 和 @click=“MutationMeth” 时,
可直接写成 @click=“ActionMeth(11)” 和 @click=“MutationMeth(22, 33)” 来给 Module 传递参数。
我在这里将 store.ts 简化了,除去了 Mutation 、 Action 和 Getter,只用 State 和 Module。
import Vue from 'vue';
import Vuex from 'vuex';
import { VuexModule, Module } from 'vuex-module-decorators';
Vue.use(Vuex);
@Module
class VuexStore extends VuexModule {
public static namespaced = true; // 静态的
public foo: number = 2222;
}
export default new Vuex.Store({
modules: {
test: VuexStore,
},
});
以上重点是 VuexStore 的 namespaced 字段,
随后就是暴露实例化的位置,test 表示名为 test 的命名空间。
这里也除去了 Mutation 、 Action 和 Getter,只用 State 和 Module。
<template>
<div class="home">
<h1>This is an home pageh1>
{{ stateFoo }}
div>
template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { State, namespace } from 'vuex-class';
@Component
export default class Home extends Vue {
@namespace('test').State('foo') private stateFoo!: number; // 重命名
}
script>
这里指定了 stateFoo 这个字段是 test 命名空间下的 foo 字段的重命名。