需求
使用vue.js 3 用户登陆之后,router 进行replace更新,但 App.vue 中的导航没有更新。 解决办法,使用vuex 的 store,就是先将这个提交在 store里面,然后进行 this.$store.commit('realoadLogin') 触发更新。
示例
App.vue
# App.vue
<script>
import {RouterLink, RouterView} from 'vue-router'
export default {
computed: {
isLogin() {
return this.$store.state.authed
}
},
created() {
this.$store.commit('login')
}
}
</script>
<template>
<div class="container">
<nav class="nav" v-if="isLogin">
<RouterLink to="/" class="nav-link" :class="{'active': 1}">首页</RouterLink>
<RouterLink to="/logout" class="nav-link">退出</RouterLink>
</nav>
<RouterView/>
</div>
</template>
<style>
</style>
JS
import {createApp} from 'vue'
import App from './App.vue'
import router from './router'
import store from './plugins/store.js'
const app = createApp(App)
app.use(router)
app.use(store)
app.mount('#app')
LoginForm.vue
<script>
import axios from 'axios'
export default {
data() {
return {
code: "",
error: ""
}
},
methods: {
login() {
this.$axios.post(`/login`, {
}).then(resp => {
localStorage.setItem('jwt', resp.data.jwt || '')
this.$store.commit('reloadLogin')
this.$router.replace({name: 'home'})
}).catch(e => {
this.error = e
})
}
}
}
</script>
plugins/store.js
import {createStore} from 'vuex'
const store = createStore({
state() {
return {
count: 0,
authed: false
}
},
mutations: {
reloadLogin(state) {
this.state.authed = (localStorage.getItem('jwt') || '') !== ''
},
increment(state) {
state.count++
}
}
})
export default store
|