vue項目退出登錄清除store數(shù)據(jù)的三種方法
方法一:(不友好,頁面會白屏,不推薦使用)
在退出登錄的loginOut 方法里面:
window.location.reload()
方法二 : (不會出現(xiàn)白屏,推薦使用)
利用v-if控制router-view,在根組件APP.vue中實現(xiàn)一個刷新方法
<template> <router-view v-if="isRouterAlive"/> //路由的組件 </template> <script> export default { data () { return { isRouterAlive: true } }, methods: { reload () { this.isRouterAlive = false this.$nextTick(() => (this.isRouterAlive = true)) } } } </script>
然后使用的時候調(diào)用: this.reload() 方法
方法三 : vuex清除token (不會出現(xiàn)白屏,推薦使用)
vuex清除token
由于項目中需要一個用戶登出的功能,而數(shù)據(jù)放在Vuex中在登出沒有刷新時數(shù)據(jù)并不會更新
所以找到了這樣一個很不錯的方法
將state以各種方式保存
注冊時調(diào)用函數(shù)賦值
清空時再將保存的state賦值替換當(dāng)前的state
over
1. 首先默認state時要用新的方法注冊
把數(shù)據(jù)寫在函數(shù)的返回值中(其他方法也可以只要能調(diào)用)
const getDefaultState = () => { return { token: getToken(), name: '', avatar: '', permList:[] } }
2. 給Vuex中的state賦值并注冊
const state = getDefaultState(); const store = new Vuex.Store({ modules: { app, settings, state, permissions }, getters })
3. 在mutations中定義方法
RESET_STATE: (state) => { Object.assign(state, getDefaultState()) },
4. 頁面中使用
commit('RESET_STATE');
5. 全部完整代碼如下:
const getDefaultState = () => { return { token: getToken(), name: '', avatar: '' } } const state = getDefaultState() const mutations = { RESET_STATE: (state) => { Object.assign(state, getDefaultState()) }, } logout({ commit, state }) { return new Promise((resolve, reject) => { logout(state.token).then(() => { removeToken() // must remove token first resetRouter() commit('RESET_STATE') resolve() }).catch(error => { reject(error) }) }) },
6. 退出登錄
組件中派發(fā)任務(wù)
async logout() { await this.$store.dispatch("user/logout"); this.$router.push(`/login?redirect=${this.$route.fullPath}`); }, },
親自測試有效:
第三種方法強烈推薦使用。
總結(jié)
到此這篇關(guān)于vue項目退出登錄清除store數(shù)據(jù)的三種方法的文章就介紹到這了,更多相關(guān)vue退出登錄清除store數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入探究Vue2響應(yīng)式原理的實現(xiàn)及存在的缺陷
Vue的響應(yīng)式數(shù)據(jù)機制是其核心特性之一,它能夠自動追蹤數(shù)據(jù)的變化,并實時更新相關(guān)的視圖,然而,Vue2中的響應(yīng)式數(shù)據(jù)機制并非完美無缺,本文將探討Vue2響應(yīng)式原理及其存在的缺陷2023-08-08vue2使用ts?vue-class-component的過程
vue-property-decorator?是一個?Vue.js?的裝飾器庫,它提供了一些裝飾器來讓你在?Vue?組件中定義屬性、計算屬性、方法、事件等,本文給大家介紹vue2使用ts?vue-class-component的相關(guān)知識,感興趣的朋友一起看看吧2023-11-11在vue中利用全局路由鉤子給url統(tǒng)一添加公共參數(shù)的例子
今天小編就為大家分享一篇在vue中利用全局路由鉤子給url統(tǒng)一添加公共參數(shù)的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11