vue结合ts 使用es6写法获取store中的状态
vue要想使用es6写法,首先需要安装装饰器 vue-property-decorator;
项目结合ts进行的初始化,需要在Script开始标签中添加 lang=“ts”, 如
1.创建store 名为index.ts
idnex.ts中的state,mutations,actions,getters可以写着同一个文件中,大型项目会被差分开
import Vue from "vue";
import Vuex from "vuex";
import state from "@/store/state";
import mutations from "@/store/mutations";
import actions from "@/store/actions";
import getters from "@/store/getters";
import task from "@/store/modules/task.module";
Vue.use(Vuex);
export default new Vuex.Store({
state,
mutations,
actions,
getters,
modules: {
task,
}
});
1.1创建task模块store/module/task.module.js
const state = {
params: {
name: "张三"
}
};
const mutations = {
setParams: (state, params) => {
state.params = params;
}
};
const actions = {
setParams({ commit }, params) {
commit("setParams", params);
}
};
const getters = {
getParams: state => {
return state.params;
}
};
export default {
namespaced: true,
state,
mutations,
actions,
getters
};
2.改写script中的代码
//lang="ts"表示这里面的写法为typeScript而不是js
<script lang="ts">
//导入es6写法的装饰器类
import {Component, Prop} from "vue-property-decorator";
import Vue from "vue";
//导入组件
import IdentityCheck from "./IdentityCheck.vue";
//调入stroe中getters、actions
import {mapGetters, mapActions} from "vuex";
//用装饰器注解标注类
@Component({
//注册组件
components: {
IdentityCheck
},
//获取store中的getters
computed: mapGetters([
"task/getParams"
]),
//获取store中的actions
methods: mapActions([
"task/setParams"
])
})
export default class FieldSurveyMain extends Vue {
active = 0;
maxActive = 0;
//定义prop 类型 默认值 !为非空断言
@Prop({type: String,default: "0"}) fieldSurveyActive!: string;
titles = [
{ name: "身份核查", bsno: 1 },
];
//映射store中的getters里面的方法
// task 为module名称
"task/getParams"!: any;
//映射上面注解中的方法
"task/setParams"!: any;
mounted() {
this.active = Number.parseFloat(this.fieldSurveyActive);
this.maxActive = this.active;
console.log(this["task/getParams"]);
this["task/setParams"]({name: "王三", age: 26});
console.log(this["task/getParams"]);
//打印之后就可以看到task中state的改变
}
//typscrit指定入参的类型
clickStep(index:number) {
//如果切换的节点是未做的节点,返回
if (index > this.maxActive) {
return;
}
this.active = index;
}
goForward() {
//下一步节点只能通过,下一步按钮切换
this.active++;
this.maxActive = this.active;
}
}
</script>
启动项目之后,可以看到前后两次打印状态中的数据改变;