解决因为数据变化,页面没有变化的情况 , 复习一下使用 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']
    }
  },
相关推荐
●VON6 分钟前
React Native for OpenHarmony:项目目录结构与跨平台构建流程详解
javascript·学习·react native·react.js·架构·跨平台·von
We་ct17 分钟前
LeetCode 36. 有效的数独:Set实现哈希表最优解
前端·算法·leetcode·typescript·散列表
爱吃大芒果23 分钟前
Flutter for OpenHarmony 实战:mango_shop 路由系统的配置与页面跳转逻辑
开发语言·javascript·flutter
qq_1777673727 分钟前
React Native鸿蒙跨平台实现消息列表用于存储所有消息数据,筛选状态用于控制消息筛选结果
javascript·react native·react.js·ecmascript·harmonyos
weixin_3954489128 分钟前
main.c_cursor_0129
前端·网络·算法
沐雪架构师40 分钟前
LangChain 1.0 Agent开发实战指南
开发语言·javascript·langchain
2501_940007891 小时前
Flutter for OpenHarmony三国杀攻略App实战 - 战绩记录功能实现
开发语言·javascript·flutter
摘星编程1 小时前
React Native + OpenHarmony:自定义useEllipsis省略号处理
javascript·react native·react.js
2401_859049081 小时前
git submodule update --init --recursive无法拉取解决
前端·chrome·git
这是个栗子1 小时前
【Vue代码分析】前端动态路由传参与可选参数标记:实现“添加/查看”模式的灵活路由配置
前端·javascript·vue.js