vue模拟登陆功能,vuex登陆后显示用户信息

vue模拟后台登陆功能

vue模拟登陆功能,vuex登陆后显示用户信息_第1张图片

 

利用vuex进行存储数据实现登陆后显示个人信息功能

1、在vuex(store.js)中创建数据状态

state:

isLogin: false, //用来显示是否登陆

currentuser: null //用来显示用户信息是否显示

getter:

getIsLogin: state => state.isLogin,

getCurrentuser: state => state.currentuser

vue模拟登陆功能,vuex登陆后显示用户信息_第2张图片

2、在header组件中展示是否显示用户信息

  • {{current}}
  • [退出]
  • 登陆
  • vue模拟登陆功能,vuex登陆后显示用户信息_第3张图片

    3、在header组件中获取当前数据的显示状态

    computed: {

    isLogin: function() {

    return this.$store.getters.getIsLogin;

    },

    current: function() {

    return this.$store.getters.getCurrentuser;

    }

    }

    vue模拟登陆功能,vuex登陆后显示用户信息_第4张图片

    4、在login组件中 登陆跳转页面之前需要我们进行存储当前的用户信息(这次存储在action中 在应用mutations的方法 也可以直接存在mutations中进行数据的操作)

    注释:mutations 是更改数据状态,在组件中调用需要用 commit('函数名',data) data传过去的数据

            action 是应用mutations,需要用dispatch进行传递数据 dispatch('函数名',数据)

     

    if (isUser != null && isUser.length > 0) {

    this.$store.dispatch("setUser", isUser[0].email);

    this.$router.push("/");

    } else {

    this.$store.dispatch("setUser", null);

    alert("当前用户不存在");

    }

    vue模拟登陆功能,vuex登陆后显示用户信息_第5张图片

    5、在store中进行逻辑判断

    actions: { //应用mutations

    setUser({ commit }, user) {

    commit("userSatus", user)

    }

    }

    mutations: { //用来更改数据状态

    //更改用户的状态信息  如果用户信息没有则保存,如果有则进行清空

    userSatus(state, user) {

    if (user) {

    state.currentuser = user;

    state.isLogin = true

    } else {

    state.currentuser = null;

    state.isLogin = false

    }

    }

    }

    vue模拟登陆功能,vuex登陆后显示用户信息_第6张图片

    6、成功啦!成功之后设置退出的功能,退出后用户信息的null掉,用到了组建内路由守卫

  • [退出]
  •   //header中退出调转到登录页面

    登录页面中进行路由守卫,推出后进行清空用户信息

    beforeRouteEnter(to, from, next) {

    // ...

    next(vm => {

    vm.$store.dispatch("setUser", null);

    });

    },

     

     

     

     

    你可能感兴趣的:(vue)