动态将用户重定向到登录页面

时间:2018-09-03 22:10:18

标签: vue.js vuex

我有Vue.js应用程序,其中某些路由要求用户登录,而其他路由(例如登录页面)是公共的。

created() {
    let context = this;
    context.axios.create({withCredentials: true}).get(`${context.$store.getters.getApiUrl}/session/`).then(response => {
      context.$store.commit('loginUser');
      context.$store.commit('setUser', response.data.data);
    }, error => { 
       /* 
          This indicates a 401 unathorized response that indicates 
          the session cookie has expired
       */
      context.$store.commit('logoutUser')
    });
},
computed: {
    authorized: {
        get: function() {
            let authenticated = this.$store.getters.getUserAuthStatus;
            let route = this.$route;
            if (authenticated !== true && route.meta.requiresLogin === true) {
              return false;
            }
            else {
                return true;
            }
        }
    }
},
watch: {
    authorized: function(val) {
        if (val === false) {
            this.$router.push('/signin');
            this.$store.commit('setGlobalInfo', 'Please sign in first.');
        }
    }
}

基本上,当用户打开应用程序时,我向服务器上的受保护路由发送了一个请求。根据响应,我要么登录用户(并将Vuex authenticated的状态设置为true),要么注销他们。

我添加了观察者,因为如果login计算出的属性更改,我想自动将用户重定向到authorized。但是我还没有开始工作。 authorized属性可以正确计算,但观察者函数永远不会触发。

我的理解是,只要给Vue计算的属性使用相同的名称(即“授权”),就可以观看它们。我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

似乎我需要在观察者上设置deep: true

computed: {
    authorized: {
        let authenticated = this.$store.getters.getUserAuthStatus;
        let route = this.$route;
        if (authenticated !== true && route.meta.requiresLogin === true) {
            return false;
        }
        else {
            return true;
        }
    }
},
watch: {
    authorized: {
        handler: function(val) {
            if (val === false) {
                this.$router.push('/signin');
                this.$store.commit('setGlobalInfo', 'Please sign in first.');
            }
        },
        deep: true;
}