如何观察令牌是否在localStorage中注册,并相应地更改绑定属性的值



当前,只要用户使用正确的凭据登录,就会在本地存储中保存一个令牌。现在我正试图在用户登录后隐藏登录和注册。

我目前的代码运行得相对不错,但我注意到,当用户登录时,登录和注册路线不会消失,直到页面刷新,这不是很像SPA。

为什么会发生这种情况?

<template>
<div class="nav-header">
<div class="wrapper">
<ul class='nav-ul'>
<router-link to="/" tag='li' active-class='active' exact><li><a>Home</a></li></router-link>
<router-link to="/signup" v-if="!isLoggedIn" tag='li' active-class='active' exact><li><a>Sign Up</a></li></router-link>
<router-link to="/signin" v-if="!isLoggedIn" tag='li' active-class='active' exact><li><a>Sign In</a></li></router-link>
</ul>
</div>
</div>
</template>
<script>
export default {
computed: {
isLoggedIn() {
return !!window.localStorage.getItem('token')
}
}
}
</script>

App.vue

<template>
<div id="app">
<app-header></app-header>
<router-view></router-view>
</div>
</template>
<script>
import Header from './components/header.vue';
export default {
components: {
appHeader: Header
}
}
</script>

Sigin.vue

<template>
<div>
<input v-model="email" placeholder="Your Email...">
<input v-model="password" placeholder="Your Password...">
<button v-on:click.prevent="signin" type="submit" name="submit">Submit</button>
</div>
</template>
<script>
import axios from 'axios'
axios.defaults.baseURL = 'http://94.155.24.68/api';
export default {
data: function() {
return {
email: '',
password: ''
}
},
methods: {
signin: function(){
axios.post('/signin', {
email: this.email,
password: this.password
})
.then((response) => {
console.log(response);
const token = response.data.token;
localStorage.setItem('token', token);
}).catch((error) => console.log(error));
}
}
}
</script>

这不起作用的原因是,您正试图监视非响应式localStorage上的更改。

为了使其具有反应性,我倾向于使用Vue.prototype创建一个全局Vue实例(允许您在所有组件中使用它)

Vue.prototype.$localStorage = new Vue({
data: { 
// token property returning the ls token value 
token: window.localStorage.getItem('token') 
},
watch:{ 
// watcher listening for changes on the token property
// to ensure the new value is written back to ls 
token(value){ window.localStorage.setItem('token', value) } 
}
})
//  you can now access the token in all your components using
//  this.$localStorage.token            get the token value
//  this.$localStorage.token = 'tkn';   set the token value  

演示https://codepen.io/jakob-e/pen/LMJEYV?editors=1010

要在您的解决方案中实现它,您可以执行以下操作:

// in the header component
computed: {
isLoggedIn(){ return this.$localStorage.token !== ''; }
}
// in the signin component
signin(){
axios.post('/signin', {
email: this.email,
password: this.password
})
.then((response) => {
console.log(response);
const token = response.data.token;
this.$localStorage.token = token;  
})
.catch((error) => console.log(error));
}

最新更新