vue全家桶-vuex(一)

news2024/9/27 15:26:28

vue全家桶-vuex(一)

  • 1.Vuex概述
  • 2.Vuex中的核心特性
    • A.State
      • 1.this.$store.state.全局数据名称-组件访问State中的数据的第一种方式
      • 2.组件访问State中的数据的第二种方式:按需导入
    • B.Mutation
      • 1.this.$store.commit是触发Mutation的第一种方式
      • 2.触发Mutation的第二种方式,按需导入
    • C.Action
      • 1.this.$store.dispatch()是触发actions的第一种方式
      • 2.触发actions的第二种方式:按需导入
    • D.Getter
      • 1.使用getters的第一种方式
      • 2.使用getters的第二种方式
  • 3.代码总结

使用
在这里插入图片描述

文件内容:https://download.csdn.net/download/ingenuou_/87360207

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import app from './modules/app'
import settings from './modules/settings'
import user from './modules/user'
import system from './modules/system'

Vue.use(Vuex)

const store = new Vuex.Store({
    modules: {
        app,
        settings,
        user,
        system
    },
    getters
})

export default store

getters.js

const getters = {
    sidebar: state => state.app.sidebar,
    device: state => state.app.device,
    token: state => state.user.token,
    avatar: state => state.user.avatar,
    name: state => state.user.name,
    currentuserinfo: state => state.system.currentuserinfo,
    count: state => state.system.count,
}
export default getters

system.js

  const system = {
      namespaced: true,
      state: {
          currentuserinfo: {},
          count: 0,
      },
      mutations: {
          SET_CURRENTUSERINFO: (state, currentuserinfo) => {
              state.currentuserinfo = currentuserinfo
          },
          SET_COUNT: (state, count) => {
              state.count = count
          },
      }
  }
  export default system

全局使用:
main.js文件中

import store from './store'

new Vue({
    el: '#app',
    router,
    store,
    render: h => h(App)
})

1.Vuex概述

Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间的数据共享

使用Vuex管理数据的好处:
A.能够在vuex中集中管理共享的数据,便于开发和后期进行维护
B.能够高效的实现组件之间的数据共享,提高开发效率
C.存储在vuex中的数据是响应式的,当数据发生改变时,页面中的数据也会同步更新

2.Vuex中的核心特性

vuex中的主要核心概念如下:

  1. State
  2. Mutation
  3. Action
  4. Getter

A.State

State提供唯一的公共数据源,所有共享的数据都要统一放到Store中的State中存储
例如,打开项目中的store.js文件,在State对象中可以添加我们要共享的数据,如:count:0

在这里插入图片描述

在组件中访问State的方式:
1).this.$store.state.全局数据名称  如:this.$store.state.count
2).先按需导入mapState函数: import { mapState } from 'vuex'
然后数据映射为计算属性: computed:{ ...mapState(['全局数据名称']) }

1.this.$store.state.全局数据名称-组件访问State中的数据的第一种方式

//访问
console.log("1111",this.$store.state.system.count);
<h3>当前最新的count值为:{{$store.state.system.count}}</h3>

2.组件访问State中的数据的第二种方式:按需导入

在这里插入图片描述

 2).先按需导入mapState函数: import { mapState } from 'vuex'
 //将全局数据,用展开运算符映射为当前组件的计算属性
   // 然后数据映射为计算属性: computed:{ ...mapState(['count']) }
 mapState()可以传入对象或者数组
 传入数组用法: mapState(['counte', 'name','age'])
// 传入对象用法:可以重命名store中的数据
  ...mapState({
   sCounter: state => state.name,
   ......
 })
 computed:{
   ...mapState({
      count: state => state.system.count,
      ......
    }), 
  }
 

B.Mutation

Mutation用于修改变更$store中的数据

  1. 只能通过Mutation变更Store数据,不可以直接操作Store中的数据
  2. 通过这种方式虽然操作起来稍微繁琐点,但是可以集中监控所有的数据变化

1.this.$store.commit是触发Mutation的第一种方式

在这里插入图片描述

1.定义:

  const system = {
      namespaced: true,
      state: {
          count: 0,
      },
      mutations: {
          add(state) {
             //变更状态
              state.count++
          }
      }
  }
  export default system

2.使用

<template>
  <div>
    <h3>当前最新的count值为:{{$store.state.system.count}}</h3>
    <el-button type="primary" @click="btnHandler1">+1</el-button>
  </div>
</template>

<script>
export default {
  name: 'Addition',
  props: {
  },
  data() {
    return {
    }
  },
  computed: {},
  mounted() {},
  methods: {
    btnHandler1() {
      this.$store.commit("system/add")
    },
  }
}
</script>

<style scoped>
</style>

1.传参—定义

mutations: {
          add(state) {
              state.count++
          },
          addN(state, step) {
              state.count += step
          }
      }

2.传参-使用

methods: {
    btnHandler1() {
      this.$store.commit("system/add")
    },
    btnHandler2(val){
      // commit 的作用就是调用某个mutation函数
      this.$store.commit("system/addN",val)
    },

  }

2.触发Mutation的第二种方式,按需导入

在这里插入图片描述

从vuex中按需导入mapMutations 函数

import { mapMutations } from 'vuex'

通过刚才导入的mapMutations 函数,将需要的mapMutations 函数,映射为当前组件的methods方法:

sub(state) {
     state.count--
},
subN(state, step) {
     state.count -= step
},
method:{
    ...mapMutations({
      sub: 'system/sub'
    }),
    btnHandler1(){
      this.sub()//直接引用
    },
    btnHandler2(val){
      this.subN(val)
    },
}

C.Action

Action用于处理异步任务
如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,但Action中还是要通过出发Mutation的方式间接变更数据
在这里插入图片描述

1.this.$store.dispatch()是触发actions的第一种方式

actions: {
          addAsync(content) {
              setTimeout(() => {
                  // 在actions中,不能直接修改state中的数据
                  // 必须通过content.commit() 去触发某个mutations才行
                  content.commit('add')
              }, 1000)
          }

      }
methods: {
    // 异步的让count自增+1
    btnHandler3(){
      // 这里的dispatch函数,专门用来触发actions
      this.$store.dispatch('system/addAsync')
    },
 }

actions携带参数
触发actions异步任务时携带参数
在这里插入图片描述

      actions: {
          addNAsync(content, step) {
              setTimeout(() => {
                  // 在actions中,不能直接修改state中的数据
                  // 必须通过content.commit() 去触发某个mutations才行
                  content.commit('addN', step)
              }, 1000)
          },

      }
methods: {
    btnHandler4(){
      // 这里的dispatch函数,专门用来触发actions,传参
      this.$store.dispatch('system/addNAsync',3)
    },
 }

2.触发actions的第二种方式:按需导入

在这里插入图片描述

      actions: {
          subAsync(content) {
              setTimeout(() => {
                  // 在actions中,不能直接修改state中的数据
                  // 必须通过content.commit() 去触发某个mutations才行
                  content.commit('sub')
              }, 1000)
          },
          subNAsync(content, step) {
              setTimeout(() => {
                  // 在actions中,不能直接修改state中的数据
                  // 必须通过content.commit() 去触发某个mutations才行
                  content.commit('subN', step)
              }, 1000)
          },
}
import {mapActions } from 'vuex'

  methods:{
    ...mapActions({
      subAsync: 'system/subAsync',
      subNAsync: 'system/subNAsync',
    }),
    btnHandler3(){
      this.subAsync()
    },
    btnHandler4(){
      this.subNAsync(3)
    },
    }

D.Getter

Getter用于对Store中的数据进行加工处理形成新的数据
它只会包装Store中保存的数据,并不会修改Store中保存的数据,当Store中的数据发生变化时,Getter生成的内容也会随之变化
打开store.js文件,添加getters,如下:
在这里插入图片描述

1.使用getters的第一种方式

//system.js文件中的  getters中的showNum
<h3>{{$store.getters['system/showNum']}}</h3>
console.log('$store.state',this.$store.getters['system/showNum']);

2.使用getters的第二种方式

<h3>{{showNum}}</h3>
  computed: {
    ...mapGetters({
      showNum: 'system/showNum',
    })
  },

3.代码总结

system.js

  const system = {
      namespaced: true,
      state: {
          currentuserinfo: {},
          count: 0,
      },
      //   只有mutations中定义的函数,才有全力修改state中的数据
      mutations: {
          //   SET_CURRENTUSERINFO: (state, currentuserinfo) => {
          //       state.currentuserinfo = currentuserinfo
          //   },
          //   SET_COUNT: (state, count) => {
          //       state.count = count
          //   },
          add(state) {
              state.count++
          },
          addN(state, step) {
              state.count += step
          },
          sub(state) {
              state.count--
          },
          subN(state, step) {
              state.count -= step
          },
      },
      actions: {
          addAsync(content) {
              setTimeout(() => {
                  // 在actions中,不能直接修改state中的数据
                  // 必须通过content.commit() 去触发某个mutations才行
                  content.commit('add')
              }, 1000)
          },
          addNAsync(content, step) {
              setTimeout(() => {
                  // 在actions中,不能直接修改state中的数据
                  // 必须通过content.commit() 去触发某个mutations才行
                  content.commit('addN', step)
              }, 1000)
          },
          subAsync(content) {
              setTimeout(() => {
                  // 在actions中,不能直接修改state中的数据
                  // 必须通过content.commit() 去触发某个mutations才行
                  content.commit('sub')
              }, 1000)
          },
          subNAsync(content, step) {
              setTimeout(() => {
                  // 在actions中,不能直接修改state中的数据
                  // 必须通过content.commit() 去触发某个mutations才行
                  content.commit('subN', step)
              }, 1000)
          },

      },
      getters: {
          //添加了一个showNum的属性
          showNum(state) {
              return '最新的count值为:【' + state.count + '】';
          }
      }
  }
  export default system

src\views\learnVuex\index.vue

<template>
  <div>
    <my-addition ></my-addition>
    <p>----------------------</p>
    <my-subtranction ></my-subtranction>

  </div>
</template>

<script>
// 导入
import Addition from '@/components/Addition';
import Subtranction from '@/components/Subtranction';
// import Subtranction from '../../components/Addition';
export default {
  name: 'learnVuex',
  props: {},
  //   注册
  components: {
    'my-addition': Addition,
    'my-subtranction': Subtranction
  },
  data() {
    return {

    }
  },
  computed: {},
  mounted(){
    console.log("1111",this.$store.state.system.count);

  },
}
</script>

<style scoped>
</style>

src\components\Addition\index.vue

<template>
  <div>
    <h3>当前最新的count值为:{{$store.state.system.count}}</h3>
    <h3>{{$store.getters['system/showNum']}}</h3>
    <el-button type="primary" @click="btnHandler1">+1</el-button>
    <el-button type="primary" @click="btnHandler2(2)">+2</el-button>
    <el-button type="primary" @click="btnHandler2(3)">+3</el-button>

    <el-button type="primary" @click="btnHandler3">+1 Async</el-button>
    <el-button type="primary" @click="btnHandler4">+3 Async</el-button>
  </div>
</template>

<script>
export default {
  name: 'Addition',
  props: {
  },
  data() {
    return {
    }
  },
  computed: {},
  mounted() {
    console.log('$store.state',this.$store.getters['system/showNum']);
  },
  methods: {
    btnHandler1() {
      this.$store.commit("system/add")
    },
    btnHandler2(val){
      // commit 的作用就是调用某个mutation函数
      this.$store.commit("system/addN",val)
    },
    // 异步的让count自增+1
    btnHandler3(){
      // 这里的dispatch函数,专门用来触发actions
      this.$store.dispatch('system/addAsync')
    },
    // 
    btnHandler4(){
      // 这里的dispatch函数,专门用来触发actions
      this.$store.dispatch('system/addNAsync',3)
    },

  }
}
</script>
<style scoped>
</style>

\src\components\Subtranction\index.vue

<template>
<div>
  <h3>当前最新的count值为:{{count}}</h3>
  <h3>{{showNum}}</h3>
  <el-button type="primary" @click="btnHandler1">-1</el-button>
  <el-button type="primary" @click="btnHandler2(2)">-2</el-button>
  <el-button type="primary" @click="btnHandler2(3)">-3</el-button>

  <el-button type="primary" @click="btnHandler3">-1  Async</el-button>
  <el-button type="primary" @click="btnHandler4">-3  Async</el-button>
</div>
</template>

<script>
import { mapState,mapMutations,mapActions,mapGetters } from 'vuex'
export default {
  name: 'Subtranction',
  props: {},
  data(){
    return{
      
    }
  },
  computed: {
    ...mapState({
      count: state => state.system.count,
    }),
    ...mapGetters({
      showNum: 'system/showNum',
    })
   
  },
  mounted(){
    console.log("mapState",this.count);
  },
  methods:{
    ...mapMutations({
      sub: 'system/sub',
      subN: 'system/subN',
    }),
    ...mapActions({
      subAsync: 'system/subAsync',
      subNAsync: 'system/subNAsync',
    }),
    btnHandler1(){
      this.sub()
    },
    btnHandler2(val){
      this.subN(val)
    },
    btnHandler3(){
      this.subAsync()
    },
    btnHandler4(){
      this.subNAsync(3)
    },
  }
}
</script>

<style scoped>

</style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/139891.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

java学习day67(乐友商城)商品详情及静态化(Thymeleaf)

1.商品详情 当用户搜索到商品&#xff0c;肯定会点击查看&#xff0c;就会进入商品详情页&#xff0c;接下来我们完成商品详情页的展示&#xff0c; 1.1.Thymeleaf 在商品详情页中&#xff0c;我们会使用到Thymeleaf来渲染页面&#xff0c;所以需要先了解Thymeleaf的语法。 …

简明Java讲义 1:Java环境搭建与入门

目录 1、Java 介绍 2、Java 运行机制 3、Java开发环境搭建 4、Hello World&#xff01; 1、Java 介绍 Java是Sun微系统公司在1995年推出的&#xff0c;是一门面向对象的编程语言 2006年12月&#xff0c;Sun公司发布了JDK1.6&#xff08;也称作Java SE 6&#xff09; 200…

数位DP~

综述 数位DP的应用范围&#xff1a; 在某个区间内有多少个满足一定的性质 数位DP中使用的方法&#xff1a; 类似于前缀和。A到B相当于f[B] - a[A-1] 这一点尤为重要&#xff0c;因为已经弱化了边界&#xff0c;使得考虑的更少分情况讨论 ​ 1081. 度的数量 ​ 输入样例…

BGP综合实验

目录 1.拓扑图 2.实验要求 3.实验思路 4.主要配置 5.测试 6.实验总结 1.拓扑图 2.实验要求 AS1存在两个环回&#xff0c;一个地址为192.168.1.0/24&#xff1b;AS3中存在两个环回&#xff0c;一个为192.168.2.0/24&#xff1b;整个AS2的IP地址为172.16.0.0/16&#xff0c…

k8s之工作机制

写在前面 本文一起看下k8s基本架构。 1&#xff1a;Kubernetes的基本架构 k8s本身也是一种分布式架构&#xff0c;也需要在多台机器&#xff08;实体机或虚拟机无差别&#xff09;部署&#xff0c;部署的机器我们叫做节点&#xff0c;其中节点分为Master node即主节点,worke…

java使用反射给对象属性赋值

&#x1f4e2;&#x1f4e2;&#x1f4e2;&#x1f4e3;&#x1f4e3;&#x1f4e3;哈喽&#xff01;大家好&#xff0c;我是「奇点」&#xff0c;江湖人称 singularity。刚工作几年&#xff0c;想和大家一同进步&#x1f91d;&#x1f91d;一位上进心十足的【Java ToB端大厂领…

高频js手写题之实现数组扁平化、深拷贝、总线模式

前言 古人学问无遗力&#xff0c;少壮工夫老始成。纸上得来终觉浅&#xff0c;绝知此事要躬行。看懂一道算法题很快,但我们必须将这道题的思路理清、手写出来。 三道js手写题的思路和代码实现 数组扁平化 演示效果 将[1, [1, 2], [1, [2]]] 变成 [1, 1, 2, 1, 2] 第一种&…

抽象类与抽象方法

文章目录一、abstract关键字使用修饰类&#xff1a;抽象类修饰方法&#xff1a;抽象方法注意点抽象类的匿名子类一、abstract关键字使用 abstract&#xff1a;抽象的 可以修饰&#xff1a;类、方法 修饰类&#xff1a;抽象类 1、此类不可进行实例化 2、抽象类中一定有构造器…

报错 cannot import name ‘int‘ from ‘numpy‘

报错详情&#xff1a; 原因是因为np.int在numpy1.20已经被废弃掉了&#xff0c;可以通过 pip show numpy在命令行里查看。 现在使用的是np.int_ 或者 np.int32 或者 np.int64 猜测原因 但这个报错是在我自己的site-packages里的numpy的报错&#xff0c;我怀疑可能是numpy本身…

【linux】crontab

文章目录crontab简介crontab安装语法实例脚本无法执行问题常用的命令展示crontab的注意事项来源crontab简介 crontab命令常见于Unix和类Unix的操作系统之中&#xff0c;用于设置周期性被执行的指令。该命令从标准输入设备读取指令&#xff0c;并将其存放于“crontab”文件中&a…

linux系统中CAN驱动的通信方法与原理

大家好&#xff0c;今天主要和大家分享一下&#xff0c;如何使用linux系统下的CAN驱动实验。 目录 第一&#xff1a;CAN通信基本简介 第二&#xff1a;CAN通信的主要特点 第三&#xff1a;CAN通信协议 第四&#xff1a;程序代码的具体实现 第五&#xff1a;使能Linux内核自…

MATLAB-ezplot绘图函数

ezplot 函数与fplot 函数类似&#xff0c;该函数可以绘制显函数图形、隐函数图形和参数方程图形。ezplot函数的调用格式如下。 ezplot(f) ezplot(f, [ min , max ]) ezplot(f.[ xmin , xmax , ymin , ymax]) ezplot(x,y) ezplot(x,y , [tmin , tmax]) ezplot(.. . ,f…

jvm内存管理

参考链接 参考链接 Garbage Collection Concepts garbage collector的作用包括&#xff1a; 分配内存确定活着的对象不被清理回收死了的对象占用的内存 寻找和释放垃圾占用的内存空间的过程称为garbage collection一般情况下&#xff0c;整个堆或堆的一部分被填满时或者达到…

C++11 多线程

线程&#xff08;thread&#xff09;是操作系统能够进行运算调度的最小单位&#xff0c;它被包含在进程中&#xff0c;是进程中的实际运作单位&#xff0c;一条线程指的是进程中一个单一顺序的控制流&#xff0c;一个进程可以并发多个线程&#xff0c;每条线程执行不同的任务。…

FreeRTOS教程——定时器(二)

Free RTOS定时器 一、概念 一、概论 软件定时器允许设置一段时间&#xff0c;当设置的时间到达之后就执行指定的功能函数&#xff0c;被定时器 调用的这个功能函数叫做定时器的回调函数。回调函数的两次执行间隔叫做定时器的定时周期&#xff0c; 简而言之&#xff0c;当定时…

switch分支结构

一. 简介switch结合case&#xff0c;能够判断一个变量或表达式与一系列值中的某个值是否相等&#xff0c;这里的每个值都被称为一个分支。switch语句在执行时&#xff0c;会先进行值的匹配&#xff0c;匹配成功时会进入到对应case语句。再根据是否有 break语句&#xff0c;判断…

手把手教你正确地创建并配置一个SpringBoot项目

文章目录1. 安装Spring Boot Helper插件2. 创建SpringBoot项目3. 配置SpringBoot项目4. 选择修改配置&#xff08;选做&#xff09;4.1 修改端口号4.2 其他自定义配置5. SpringBoot热部署本文主要是针对IDEA社区版用户的&#xff0c;如果你是专业版的用户&#xff0c;那么是可以…

RHCE第三天之ssh远程连接服务

文章目录一、连接加密技术简介二、SSH的工作过程三、 SSH远程连接服务配置四、SSH实验SSH&#xff08;Secure Shell Protocol&#xff0c;安全的壳程序协议&#xff1a; 它可以通过数据包加密技术将等待传输的数据包加密后再传输到网络上。ssh协议本身提供两个服务器功能&#…

爬虫学习-验证码识别

反爬机制&#xff1a;验证码&#xff0c;识别验证码图片中的数据&#xff0c;用于模拟登陆识别验证码的操作人工肉眼识别(不推荐&#xff09;第三方自动识别(推荐)python第三方库&#xff1a;tesseract、ddddocr(7条消息) 小白都能轻松掌握&#xff0c;python最稳定的图片识别库…

探索用于NLP的Gensim库

Gensim的名字源自于"Generate Similar," 这个词是指Gensim可以用于生成类似的文本。这个词也可以被解释为"Generative Similarity," 表示Gensim可以用于生成相似的文本。Gensim是一个用于文本处理的库,可以用于计算文本之间的相似度,以及生成类似的文本。…