Vuex常用技巧总结

2020-06-08  本文已影响0人  Roct

创建一个store文件夹, 内部有命名对应的文件


image.png
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
})

let isLogin = false
try {
    if (Cookies.get("isLogin")) {
        isLogin = Cookies.get("isLogin")
    }

} catch (error) {}
export default {
    isLogin: isLogin, // 是否登录
}
export default {
   saveIsLogin(state, isLogin) {
        state.isLogin = isLogin
        try {
            Cookies.set('isLogin', isLogin, {
                expires: 2
            });
        } catch (e) {
            alert("登录失败")
        }
    },
}
export default {
   saveIsLogin(ctx, isLogin) {
        ctx.commit('saveIsLogin', isLogin)
    },
}
<template></template>
<script>
import { mapActions } from "vuex";
export default {
    name: "PhoneLogin",
    methods: {
      login() {
        this.saveIsLogin(true);
      },
      ...mapActions([
            "saveIsLogin"
        ])
    }
}
</script>
<template>  
     <div>{{isLogin}}</div>
</template>
<script>
import { mapState } from "vuex";
export default {
    name: "PhoneLogin",
    computed: {
      ...mapState({
            isLogin: "isLogin"
        }),
    }
}
</script>
上一篇 下一篇

猜你喜欢

热点阅读