美文网首页
Vuex常用技巧总结

Vuex常用技巧总结

作者: Roct | 来源:发表于2020-06-08 22:54 被阅读0次
  • 将vuex的store.js改为state, mutations, actions三部分

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


image.png
  • 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>

相关文章

网友评论

      本文标题:Vuex常用技巧总结

      本文链接:https://www.haomeiwen.com/subject/gvtjtktx.html