-
将vuex的store.js改为state, mutations, actions三部分
创建一个store文件夹, 内部有命名对应的文件

-
store.js代码
import Vue from 'vue'
import Vuex from 'vuex'
import actions from '@/store/actions'
import mutations from '@/store/mutations'
import state from '@/store/state'
Vue.use(Vuex)
export default new Vuex.Store({
state,
mutations,
actions
})
-
state.js代码
let isLogin = false
try {
if (Cookies.get("isLogin")) {
isLogin = Cookies.get("isLogin")
}
} catch (error) {}
export default {
isLogin: isLogin, // 是否登录
}
-
mutations.js代码
export default {
saveIsLogin(state, isLogin) {
state.isLogin = isLogin
try {
Cookies.set('isLogin', isLogin, {
expires: 2
});
} catch (e) {
alert("登录失败")
}
},
}
-
actions.js代码
export default {
saveIsLogin(ctx, isLogin) {
ctx.commit('saveIsLogin', isLogin)
},
}
-
写入vuex
<template></template>
<script>
import { mapActions } from "vuex";
export default {
name: "PhoneLogin",
methods: {
login() {
this.saveIsLogin(true);
},
...mapActions([
"saveIsLogin"
])
}
}
</script>
-
获取vuex里的数据
<template>
<div>{{isLogin}}</div>
</template>
<script>
import { mapState } from "vuex";
export default {
name: "PhoneLogin",
computed: {
...mapState({
isLogin: "isLogin"
}),
}
}
</script>
网友评论