Vuex dispatch用法

2024-05-09 10:08

本文主要是介绍Vuex dispatch用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Vuex的作用:
针对全局数据
多个组件都要使用某个变量;
但是父子组件之间传递又很麻烦
使用vuex 可以进行状态管理,可以保证数据最新

数据是存储在浏览器维护的内存中
当页面刷新f5的时候,所保存的数据被销毁

Vuex的配置:
新建文件 src\store\index.js

import Vue from 'vue'
import Vuex from 'vuex'
import common from './modules/common'
import user from './modules/user'
import metamgr from './modules/metamgr'
Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    common,
    user,
    metamgr
  },
  strict: process.env.NODE_ENV !== 'production'
})


注册vue实例
import store from '@/store'  

new Vue({
  el: '#app',
  router,
  store,

})

关于 数据 classTree 的变化
初始化
init(){
        this.$store.dispatch('metamgr/getClassTreeData')
      },

在 metamgr.js 里写入
actions 中负责处理逻辑,
将结果传入mutations(触发commit) ,
再更新state 里的对象
import API from '@/api'

const state = {
  // 类别数据 表格 树结构
  classTreeData: [],
}
const actions = {
  getClassTreeData ({commit, state}) {
    API.classes.getAllData().then(({data}) => {
      commit('getClassTreeData', data.data)
    })
  },
}
const mutations = {
  getClassTreeData (state, data) {
    state.classTreeData = data
  },
}
export default {
  namespaced: true,
  state,
  actions,
  mutations
}

 - 模块化输出


import Vue from ‘vue’
import Vuex from ‘vuex’
import common from ‘./modules/common’
import user from ‘./modules/user’
import metamgr from ‘./modules/metamgr’
Vue.use(Vuex)

export default new Vuex.Store({
modules: {
common,
user,
metamgr
},
strict: process.env.NODE_ENV !== ‘production’
})


1
获取

实战
user.js
import {getToken,setToken,getUser,setUser,removeToken} from '@/utils/auth'
import {login,getUserInfo,logout} from '@/api/login'

const user ={
    state:{
        token:getToken(),
        user:getUser()
    },
    actions:{
        Login({commit},form){
            return new Promise((resolve,reject)=>{
                login(form.username.trim(),form.password.trim()).then(response=>{
                    const resp = response.data
                    commit('SET_TOKEN',resp.data.token)
                    resolve(resp)
                }).catch(error =>{
                    reject(error)
                })
            })
        },
        GetUserInfo({commit,state}){
            return new Promise((resolve,reject)=>{
                getUserInfo(state.token).then((resp)=>{
                    const respUser = resp.data
                    commit('SET_USER',respUser.data)
                    resolve(respUser)
                }).catch((error)=>{
                    reject(error)
                })
            })
        }
    },
    mutations:{
        SET_TOKEN(state,token){
            state.token = token
            setToken(token)
        },
        SET_USER(state,user){
            state.user = user
            setUser(user)
        }
    },

}
export default user

permision.js
/**
 * 权限校验:
 *  Vue Router中的 前置钩子函数 beforeEach(to, from, next)
 * 当进行路由跳转之前,进行判断 是否已经登录 过,登录过则允许访问非登录页面,否则 回到登录页
 * 
 * to:  即将要进入的目标路由对象
 * from: 即将要离开的路由对象
 * next: 是一个方法,可以指定路由地址,进行路由跳转
 */

import router from './router'
import {getUserInfo} from './api/login'
import store from './store'

router.beforeEach((to,from,next)=>{
    /*获取token */
    let token = store.state.user.token
    if(!token){  //没有获取到token
        if(to.path!='/login'){
            next({path:'/login'})
        }else{
            next();
        }
    }else{
        if(to.path=='/login'){
            next();
        }else{
            var user = store.state.user.user
            if(JSON.stringify(user)!=undefined){
                next();
            }else{
                store.dispatch('GetUserInfo').then(resp =>{
                    if(resp.flag){
                        next();
                    }else{
                        next({path:'/login'})
                    }
                }).catch(error=>{

                })
            }
        }
    }

})


 

这篇关于Vuex dispatch用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/973111

相关文章

Vue和React受控组件的区别小结

《Vue和React受控组件的区别小结》本文主要介绍了Vue和React受控组件的区别小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录背景React 的实现vue3 的实现写法一:直接修改事件参数写法二:通过ref引用 DOMVu

Java实现将HTML文件与字符串转换为图片

《Java实现将HTML文件与字符串转换为图片》在Java开发中,我们经常会遇到将HTML内容转换为图片的需求,本文小编就来和大家详细讲讲如何使用FreeSpire.DocforJava库来实现这一功... 目录前言核心实现:html 转图片完整代码场景 1:转换本地 HTML 文件为图片场景 2:转换 H

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

Vue3绑定props默认值问题

《Vue3绑定props默认值问题》使用Vue3的defineProps配合TypeScript的interface定义props类型,并通过withDefaults设置默认值,使组件能安全访问传入的... 目录前言步骤步骤1:使用 defineProps 定义 Props步骤2:设置默认值总结前言使用T

Python中logging模块用法示例总结

《Python中logging模块用法示例总结》在Python中logging模块是一个强大的日志记录工具,它允许用户将程序运行期间产生的日志信息输出到控制台或者写入到文件中,:本文主要介绍Pyt... 目录前言一. 基本使用1. 五种日志等级2.  设置报告等级3. 自定义格式4. C语言风格的格式化方法

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

Java中HashMap的用法详细介绍

《Java中HashMap的用法详细介绍》JavaHashMap是一种高效的数据结构,用于存储键值对,它是基于哈希表实现的,提供快速的插入、删除和查找操作,:本文主要介绍Java中HashMap... 目录一.HashMap1.基本概念2.底层数据结构:3.HashCode和equals方法为什么重写Has

Android协程高级用法大全

《Android协程高级用法大全》这篇文章给大家介绍Android协程高级用法大全,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友跟随小编一起学习吧... 目录1️⃣ 协程作用域(CoroutineScope)与生命周期绑定Activity/Fragment 中手

Python异步编程之await与asyncio基本用法详解

《Python异步编程之await与asyncio基本用法详解》在Python中,await和asyncio是异步编程的核心工具,用于高效处理I/O密集型任务(如网络请求、文件读写、数据库操作等),接... 目录一、核心概念二、使用场景三、基本用法1. 定义协程2. 运行协程3. 并发执行多个任务四、关键

Python中yield的用法和实际应用示例

《Python中yield的用法和实际应用示例》在Python中,yield关键字主要用于生成器函数(generatorfunctions)中,其目的是使函数能够像迭代器一样工作,即可以被遍历,但不会... 目录python中yield的用法详解一、引言二、yield的基本用法1、yield与生成器2、yi