vue 中 store的使用

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-29 15:37   69   0

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

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

type.js 中存放类型常量

2. 在main中引入

test.js

import types from "../types";

// 全局变量
const state = {
  count: 6
};

// 用来获取属性
const getters = {
  count(state) {
    return state.count;
  },
  count1(state) {
    return state.count;
  },
  isEvenorOdd(state) {
    return state.count % 2 == 0 ? "偶数" : "基数";
  }
};

// 定义方法,要执行的操作 流程判断/异步请求等
const actions = {
  // increment(context) {
  //   // 包含 commit dispatch state...
  //   console.log(context);
  // },
  increment({ commit }) {
    commit(types.INCREMENT); // 修改数据的唯一方式就是显示的提交mutation
  },
  decrement({ commit, state }) {
    if (state.count > 10) {
      commit(types.DECREMENT);
    }
  },
  // 模拟异步请求
  postPromise({ commit }) {
    var test = new Promise(resolve => {
      setTimeout(() => {
        resolve();
      }, 3000);
    });
    test
      .then(() => {
        commit(types.INCREMENT);
      })
      .catch(() => {
        console.log("错了");
      });
  }
};

// 处理状态(数据)的改变
const mutations = {
  // 用一个变量来做名称 放在中括号里
  [types.INCREMENT](state) {
    // add名称同actions中的commit
    state.count++;
  },
  [types.DECREMENT](state) {
    state.count--;
  }
};

export default {
  state,
  getters,
  actions,
  mutations
};

3. 两种方式来获取

a. mapGetters,mapActions

b. this.$store 这个用得多

import { mapGetters, mapActions } from "vuex";
...
  computed: {
    count() {
      return this.$store.state.test.count;
    },
    ...mapGetters(["count1"])
  },
  methods: {
    ...mapActions(["increment", "decrement", "postPromise"]),
    add() {
      this.$store.dispatch("increment");
    },
  }

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP