在退出登录的loginOut 方法里面:
window.location.reload()
利用v-if控制router-view,在根组件APP.vue中实现一个刷新方法
- <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>
然后使用的时候调用: this.reload() 方法
vuex清除token
由于项目中需要一个用户登出的功能,而数据放在Vuex中在登出没有刷新时数据并不会更新
所以找到了这样一个很不错的方法
将state以各种方式保存
注册时调用函数赋值
清空时再将保存的state赋值替换当前的state
over
1. 首先默认state时要用新的方法注册
把数据写在函数的返回值中(其他方法也可以只要能调用)
- 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. 退出登录
组件中派发任务
- async logout() {
- await this.$store.dispatch("user/logout");
- this.$router.push(`/login?redirect=${this.$route.fullPath}`);
- },
- },
亲自测试有效:
第三种方法强烈推荐使用。
最后为了方便大家的沟通与交流请加QQ群: 625787746
请进QQ群交流:【IT博客技术分享群①】:正在跳转