2017-06-21 76 views

回答

2
  1. 集Vuex状态authenticated在登录点。
  2. 一定要清楚,当您将用户登出或启动应用程序时,您正在检查如果JWT仍然有效。
  3. 在需要该状态的组件中设置计算变量。 computed() { authenticated() => { return this.$store.state.authenticated } }

  4. 在您的模板中使用它<v-if>

祝你好运!

0

如果你不想使用Vuex,

  1. vue-persistent-state设置初始状态{ authenticated: false }
  2. 使用this.authenticated就像在vanilla Vue应用程序中一样。

实施例:

import persistentStorage from 'vue-persistent-storage'; 

const initialState = { 
    authenticated: false 
}; 
Vue.use(persistentStorage, initialState); 

Vue.component('my-login', { 
    methods: { 
    login: function() { 
     doLogin() // call to auth API 
     .then(() => { this.authenticated = true }) 
     .catch(() => { this.authenticated = false }) 
    } 
    } 
}) 

new Vue({ 
    el: '#app', 
    created: function() { 
    if (loginIsValid) { // check auth validity upon app bootup 
     this.authenticated = true 
    } else { 
     this.authenticated = false 
    } 
    } 
}) 

现在authenticated可作为中的所有组件和Vue的实例的数据。对this.authenticated的任何更改都将存储在localStorage中,您可以像在vanilla Vue应用程序中一样使用this.authenticated

如果你想理解它是如何工作的,the code是非常简单的。它基本上

  1. 增加了mixin,使所有Vue的情况下initialState可用,
  2. 表更改并将它们存储。

免责声明:我的vue-persistent-state作者。

相关问题