解决因为数据变化,页面没有变化的情况 , 复习一下使用 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']
    }
  },
相关推荐
全宝5 分钟前
🎨前端实现文字渐变的三种方式
前端·javascript·css
yanlele28 分钟前
前端面试第 75 期 - 2025.07.06 更新前端面试问题总结(12道题)
前端·javascript·面试
妮妮喔妮35 分钟前
【无标题】
开发语言·前端·javascript
fie888939 分钟前
浅谈几种js设计模式
开发语言·javascript·设计模式
谦行1 小时前
深度神经网络训练过程与常见概念
前端
Simon_He1 小时前
一个免费的在线压缩网站超越了付费的压缩软件
前端·开源·图片资源
巴巴_羊2 小时前
React Ref使用
前端·javascript·react.js
拾光拾趣录2 小时前
CSS常见问题深度解析与解决方案(第三波)
前端·css
徊忆羽菲2 小时前
Echarts3D柱状图-圆柱体-文字在柱体上垂直显示的实现方法
javascript·ecmascript·echarts
轻语呢喃2 小时前
JavaScript :字符串模板——优雅编程的基石
前端·javascript·后端