重新理解vuex

本文纯属个人意识流
store.js中基本代码:

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const cart = {};
export default new Vuex.Store({
  state: {},
  getters: {},
  mutations: {},
  actions: {},
  modules: {
    cart
  }
});

在这里插入图片描述
在state中定义状态
isLogin: false
路由中引入store.js,并使用值
import store from './store'
store.state.isLogin
或:$store.state.isLogin
使用state中的isLogin,如上图,我们无法直接修改state中的值,必须通过dispatch一个action或者commit一个mutation,
this.$store.commit('login', true)
我们使用commit提交事件,则在mutations中定事件函数login
login(state) { state.isLogin = true }
这样我们就成功修改了isLogin这个状态值

使用dispatch:
我们在actions中定义同样函数login

login(context) {
	console.log(context);
	commit('login')
}

action不能直接修改state,还是通过commit到mutation,异曲同工。
同样,修改的时候为派发login
this.$store.dispatch('login')

我们可以异步使用dispatch,接收返回结果

login(context) {
	return new Promise(resolve => {
		setTimeout(() => {
			context.commit("login");
			resolve(true);
		}, 1000);
	})
}

修改的时候接收返回值:
this.$store.dispatch("login").then(isLogin => { ...具体操作 })

commit和dispatch的区别:

commit 同步操作 this. s t o r e . c o m m i t ( ′ m u t a t i o n s 的 方 法 ′ , a r g ) d i s p a t c h 异 步 操 作 t h i s . store.commit('mutations的方法',arg) dispatch 异步操作 this. store.commit(mutationsarg)dispatchthis.store.dispatch(‘actions的方法’,arg)

简化操作:
import {mapState} from 'vuex'

computed: {
	...mapState(['isLogin'])
}

这样我们可以直接拿到isLogin状态值。
同样可以获取actions中的login,直接使用login
...mapActions(["login"])
this.login().then(...)

传参问题:
this.login({username: "tom"}).then(...)
actions中:

login(context, payload) {}		// 参数在payload中

解构

login({commit}, payload) {}		// 函数中直接使用commit

关于vuex简化:

import Vue from 'vue';

class KStore {
  constructor(options) {
    this.state = options.state;
    this.mutations = options.mutations;
    this.actions = options.actions;
    // 借用vue本身的数据响应式机制
    new Vue({
      data: {
        state: this.state
      }
    });
  }

  commit(type, payload) {
    const mutation = this.mutations[type];
    mutation(this.state, payload);
  }

  dispatch(type, payload) {
    const action = this.actions[type];
    const ctx = {
      commit: this.commit.bind(this),
      state: this.state,
      dispatch: this.dispatch.bind(this)
    };
    return action(ctx, payload);
  }
}
export default new KStore({
    state: {count:1},
    mutations: {
        add(state){
            state.count++;
        }
    },
    actions: {
      add({commit}){
        commit('add')
      }
    }
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值