赞
踩
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");
- },
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。