本文纯属个人意识流
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(′mutations的方法′,arg)dispatch异步操作this.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')
}
}
})