解决因为数据变化,页面没有变化的情况 , 复习一下使用 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']
    }
  },
相关推荐
阿珊和她的猫4 分钟前
IIFE:JavaScript 中的立即调用函数表达式
开发语言·javascript·状态模式
阿珊和她的猫12 分钟前
`require` 与 `import` 的区别剖析
前端·webpack
+VX:Fegn089517 分钟前
计算机毕业设计|基于springboot + vue在线音乐播放系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
智商偏低29 分钟前
JSEncrypt
javascript
谎言西西里31 分钟前
零基础 Coze + 前端 Vue3 边玩边开发:宠物冰球运动员生成器
前端·coze
+VX:Fegn08951 小时前
计算机毕业设计|基于springboot + vue律师咨询系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
努力的小郑1 小时前
2025年度总结:当我在 Cursor 里敲下 Tab 的那一刻,我知道时代变了
前端·后端·ai编程
GIS之路1 小时前
GDAL 实现数据空间查询
前端
OEC小胖胖1 小时前
01|从 Monorepo 到发布产物:React 仓库全景与构建链路
前端·react.js·前端框架
2501_944711432 小时前
构建 React Todo 应用:组件通信与状态管理的最佳实践
前端·javascript·react.js