最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vuejs check if cookie is set without page refresh - Stack Overflow

programmeradmin4浏览0评论

What I want to do with VUE at the moment is when the user log in the login url would disappear from the navigation.

Currently, I can log in and token cookie is set successfully in the browser. But the problem is while I won't refresh my page the login url won't disappear from the navigation bar. Heres some code examples:

Login.vue sets the cookie and redirects me to home when I log in:

if(response.status === 200 && response.data.success && response.data.token) {
  const token = response.data.token;
  this.$cookie.set('token', token);
  this.$router.push({name: 'home'});  

Then in Navigation.vue I check if the cookie exists:

<li class="nav-item" v-if="!cookie">
    <router-link class="nav-link" to="login">Login</router-link>
</li>  

data: () => {
    return {
        cookie: Vue.cookie.get('token')
    }
},

So the cookie exists after login but VUE understands that only after I hit the refresh button in browser or f5. How can I solve this so the login url disappears immediately after login?

This is my axios configuration:

const axiosInstance = axios.create({
    baseURL: 'http://localhost:3000/',
    headers: {'Content-Type': 'application/json'},
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN' 
});

axiosInstance.interceptors.request.use(
    config => {
      config.headers['Authorization'] = 'Bearer '+ Vue.cookie.get('token');
      return config;
    },
    error => Promise.reject(error)
  );

EDIT

Maybe I can achieve something with VUEX?

EDIT 2

So currently this is my solution: I've added VUEX so the token is set like this also:

  this.$cookie.set('token', token);
  this.$store.state.cookie = this.$cookie.get('token');
  this.$router.push({name: 'home'});

And in my Navbar.vue I do this:

puted: {
    cookie() {
        return this.$store.state.cookie
    }
},

and then check like this:

<span v-if="$cookie.get('token') || cookie">
    Log out
</span>
<span v-else>
    <router-link class="nav-link" to="login">Login</router-link>
</span>  

$cookie.get('token') || cookie so the cookie is from VUEX which checks it without page refresh but after page refresh VUEX state is gone. So then after page refresh $cookie.get('token') works.

What I want to do with VUE at the moment is when the user log in the login url would disappear from the navigation.

Currently, I can log in and token cookie is set successfully in the browser. But the problem is while I won't refresh my page the login url won't disappear from the navigation bar. Heres some code examples:

Login.vue sets the cookie and redirects me to home when I log in:

if(response.status === 200 && response.data.success && response.data.token) {
  const token = response.data.token;
  this.$cookie.set('token', token);
  this.$router.push({name: 'home'});  

Then in Navigation.vue I check if the cookie exists:

<li class="nav-item" v-if="!cookie">
    <router-link class="nav-link" to="login">Login</router-link>
</li>  

data: () => {
    return {
        cookie: Vue.cookie.get('token')
    }
},

So the cookie exists after login but VUE understands that only after I hit the refresh button in browser or f5. How can I solve this so the login url disappears immediately after login?

This is my axios configuration:

const axiosInstance = axios.create({
    baseURL: 'http://localhost:3000/',
    headers: {'Content-Type': 'application/json'},
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN' 
});

axiosInstance.interceptors.request.use(
    config => {
      config.headers['Authorization'] = 'Bearer '+ Vue.cookie.get('token');
      return config;
    },
    error => Promise.reject(error)
  );

EDIT

Maybe I can achieve something with VUEX?

EDIT 2

So currently this is my solution: I've added VUEX so the token is set like this also:

  this.$cookie.set('token', token);
  this.$store.state.cookie = this.$cookie.get('token');
  this.$router.push({name: 'home'});

And in my Navbar.vue I do this:

puted: {
    cookie() {
        return this.$store.state.cookie
    }
},

and then check like this:

<span v-if="$cookie.get('token') || cookie">
    Log out
</span>
<span v-else>
    <router-link class="nav-link" to="login">Login</router-link>
</span>  

$cookie.get('token') || cookie so the cookie is from VUEX which checks it without page refresh but after page refresh VUEX state is gone. So then after page refresh $cookie.get('token') works.

Share Improve this question edited Jun 18, 2019 at 7:47 frenchbaguette asked Jun 18, 2019 at 7:26 frenchbaguettefrenchbaguette 1,3396 gold badges22 silver badges43 bronze badges 4
  • What do your vue-router settings look like? – dexter Commented Jun 18, 2019 at 7:47
  • @dexter I've updated my question with solution. Can you check it ? – frenchbaguette Commented Jun 18, 2019 at 7:48
  • I would check if the cookie exitst in vue-router and then do a redirect. You could use navigation guards for that (see doc). In my app, I check the cookie and if it exists it always redirects me to home. You don't need vuex for that. – dexter Commented Jun 18, 2019 at 7:53
  • @dexter Problem is that home can view and guest and the logged in user. I would do that in router as you say if the home would be only for authenticated users. – frenchbaguette Commented Jun 18, 2019 at 7:58
Add a ment  | 

1 Answer 1

Reset to default 3

Essentially, you want to use some sort of event/signaling mechanism to inform different ponents about the change in a cookie value. Vuex is one mechanism to do that. Alternately, you can use Vue instance as an Event bus channel:

STEP 1: Create Event Bus using Vue in event.js file:

import Vue from 'vue';

export const eventBus = new Vue();

STEP 2: Import it in Login.vue and publish an event when cookie is set:

import { eventBus } from './event.js';

// ... Other code
this.$cookie.set('token', token);

// Publish event
eventBus.$emit('tokenSet', token);

STEP 3: Listen to this event in Navigation.vue:

import { eventBus } from './event.js';



data() {
    return {
        cookie: Vue.cookie.get('token')
    }
},

created() {
    eventBus.$on('tokenSet', (token) => this.cookie = token);
}

This way your cookie bees reactive by updating whenever tokenSet event is fired. With this, you really don't need to refresh the page and even if refreshed, the initial value of the cookie is read by the data function. In a large-scale application, something like Vuex or Redux is a way to go but the underlying idea is still the same.

For more details refer to this article.

发布评论

评论列表(0)

  1. 暂无评论