当前位置:   article > 正文

vue 中 store的使用_vue cli store

vue cli store

1. 在package.json查看是否已安装vuex,在store目录下

module下存放不同模块 方便区分

type.js 中存放类型常量

2. 在main中引入

test.js

  1. import types from "../types";
  2. // 全局变量
  3. const state = {
  4. count: 6
  5. };
  6. // 用来获取属性
  7. const getters = {
  8. count(state) {
  9. return state.count;
  10. },
  11. count1(state) {
  12. return state.count;
  13. },
  14. isEvenorOdd(state) {
  15. return state.count % 2 == 0 ? "偶数" : "基数";
  16. }
  17. };
  18. // 定义方法,要执行的操作 流程判断/异步请求等
  19. const actions = {
  20. // increment(context) {
  21. // // 包含 commit dispatch state...
  22. // console.log(context);
  23. // },
  24. increment({ commit }) {
  25. commit(types.INCREMENT); // 修改数据的唯一方式就是显示的提交mutation
  26. },
  27. decrement({ commit, state }) {
  28. if (state.count > 10) {
  29. commit(types.DECREMENT);
  30. }
  31. },
  32. // 模拟异步请求
  33. postPromise({ commit }) {
  34. var test = new Promise(resolve => {
  35. setTimeout(() => {
  36. resolve();
  37. }, 3000);
  38. });
  39. test
  40. .then(() => {
  41. commit(types.INCREMENT);
  42. })
  43. .catch(() => {
  44. console.log("错了");
  45. });
  46. }
  47. };
  48. // 处理状态(数据)的改变
  49. const mutations = {
  50. // 用一个变量来做名称 放在中括号里
  51. [types.INCREMENT](state) {
  52. // add名称同actions中的commit
  53. state.count++;
  54. },
  55. [types.DECREMENT](state) {
  56. state.count--;
  57. }
  58. };
  59. export default {
  60. state,
  61. getters,
  62. actions,
  63. mutations
  64. };

3. 两种方式来获取

a. mapGetters,mapActions

b. this.$store   这个用得多

  1. import { mapGetters, mapActions } from "vuex";
  2. ...
  3. computed: {
  4. count() {
  5. return this.$store.state.test.count;
  6. },
  7. ...mapGetters(["count1"])
  8. },
  9. methods: {
  10. ...mapActions(["increment", "decrement", "postPromise"]),
  11. add() {
  12. this.$store.dispatch("increment");
  13. },
  14. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/280198
推荐阅读
相关标签
  

闽ICP备14008679号