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

问题描述 投票:0回答:1

我有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中观察计算属性。我做错了什么吗?

vue.js vuex
1个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.