解决因为数据变化,页面没有变化的情况 , 复习一下使用 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']
    }
  },
相关推荐
文心快码BaiduComate11 分钟前
百度云与光本位签署战略合作:用AI Agent 重构芯片研发流程
前端·人工智能·架构
闲云一鹤41 分钟前
nginx 快速入门教程 - 写给前端的你
前端·nginx·前端工程化
QCY1 小时前
「完全理解」1 分钟实现自己的 Coding Agent
前端·agent·claude
一拳不是超人2 小时前
Electron主窗口弹框被WebContentView遮挡?独立WebContentView弹框方案详解!
前端·javascript·electron
anyup2 小时前
🔥2026最推荐的跨平台方案:H5/小程序/App/鸿蒙,一套代码搞定
前端·uni-app·harmonyos
雮尘2 小时前
如何在非 Claude IDE (TARE、 Cursor、Antigravity 等)下使用 Agent Skills
前端·agent·ai编程
icebreaker2 小时前
Weapp-vite:原生模式之外,多一种 Vue SFC 选择
前端·vue.js·微信小程序
icebreaker2 小时前
重走 Vue 长征路 Weapp-vite:编译链路与 Wevu 运行时原理拆解
前端·vue.js·微信小程序
wuhen_n2 小时前
代码生成:从AST到render函数
前端·javascript·vue.js
Lee川2 小时前
从异步迷雾到优雅流程:JavaScript异步编程与内存管理的现代化之旅
javascript·面试