vue+ts+es6获取store中的数据

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>

启动项目之后,可以看到前后两次打印状态中的数据改变;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值