解决因为数据变化,页面没有变化的情况 , 复习一下使用 vuex 的 modules

文件目录:

user.js

state: {
    token: '',
  },
mutations: {
  SET_LOCALSTORAGE(state, response){
    state.token = response.token
    localStorage.setItem('ACCESS_TOKEN', token)
  }
},
actions:{
	Login({ commit, dispatch }, data) {
		return new Promise((resolve, reject) => {
			接口 (返回 response)
			commit('SET_LOCALSTORAGE',response)  // 调用 mutations 里的 SET_LOCALSTORAGE
		})	
	})
}

getters.js :文件来自 modules 内文件(名),设置 getters ,方便二次计算,使用

const getters = {
    userInfo: state => state.user.token,(来自user.js)
    pageKey: state => state.app.pageKey,(来自app.js)
    number:state => state.app.number*2, (可重新计算处理)
}
export default getters

index.js: 使用 Vuex ,挂载

import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import app from './modules/app'
import getters from './getters'

Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
  },
 mutations: {
 },
  getters,
  modules: {
    user,
    app
  },
})
export default store
(引入mian.js 挂载到vue)

使用:

1、使用 getters 内的值

store.getters['pageKey'] 

2、调用 mutations 内的方法,设置 store 的值

store.commit('app/SET_PAGEKEY', new Date().getTime())

3、使用 actions 内 Login 方法

user/Login : 该文件下的, 
store.dispatch('user/Login') // 注意写法,是(文件/方法)
.then((res) => { // 通过返回数据进行其他操作
  if(res) {
    console.log(res,'重新获取token')
    window.location.reload()
  }
})

解决因为数据变化,页面没有变化的情况

页面:通过设置 key 解决因为数据变化,页面没有变化的情况
<div id="app" :key="pageKey">
    <transition :name="transitionName">
      <router-view v-if="isRouterAlive" />
    </transition>
 </div>

js 使用计算属性,在数据变化时候及时更新 key 

computed: {
    transitionName() {
      return this.$store.state.direction || ''
    },
    pageKey() {
      return store.getters['pageKey']  // 因为放到了 getters ,直接使用 ['pageKey'] ,否则  ['app/pageKey']
    }
  },
相关推荐
bin91531 小时前
DeepSeek 助力 Vue 开发:打造丝滑的复制到剪贴板(Copy to Clipboard)
前端·javascript·vue.js·ecmascript·deepseek
晴空万里藏片云3 小时前
elment Table多级表头固定列后,合计行错位显示问题解决
前端·javascript·vue.js
曦月合一3 小时前
html中iframe标签 隐藏滚动条
前端·html·iframe
奶球不是球3 小时前
el-button按钮的loading状态设置
前端·javascript
kidding7233 小时前
前端VUE3的面试题
前端·typescript·compositionapi·fragment·teleport·suspense
无责任此方_修行中4 小时前
每周见闻分享:杂谈AI取代程序员
javascript·资讯
Σίσυφος19005 小时前
halcon 条形码、二维码识别、opencv识别
前端·数据库
学代码的小前端5 小时前
0基础学前端-----CSS DAY13
前端·css
dorabighead6 小时前
JavaScript 高级程序设计 读书笔记(第三章)
开发语言·javascript·ecmascript
css趣多多6 小时前
案例自定义tabBar
前端