简体   繁体   中英

Vuex state is not updating before load vue component?

Sometimes token commits to Vuex store and sometimes not.

userLogin() {
  axios.post('api/login', this.logindata,)            
  .then(response => {
    let token = JSON.parse(localStorage.getItem('token'));

    this.$store.commit('setToken', token);
    this.logindata = {};
    this.loaded = true;
    this.success = true;
    this.$router.push({path: '/'});
  });
}

Here is the store.js :

export default new Vuex.Store({
  state: {
    token: JSON.parse(localStorage.getItem('token')),
    isLoggedIn: !!localStorage.getItem('token'),
    cart: []
  },
  mutations: {
    setToken(state, token) {
      state.token = token;
    },
  }
});

Here is Vue Frontend:

mounted: function () {       
  if (!this.$store.state.isLoggedIn) {
    this.$router.push('/login')
  }
}

Result: sometimes it redirects to login and sometimes not. Any help about it?

I would make a v-if on the component you want to load only after login where you would have a computed property bound to it, that way you have a listener.

<myComponent v-if="computedProperty"/>
computed: {
 computedProperty(){
   return this.$store.state.isLoggedIn
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM