Vuex ——详细介绍

2023-11-02

Vuex 是一个专门为 Vue.js 应用程序开发的状态管理模式,它采用集中式存储管理应用的所有组件状态,并以相应的规则保证状态以一种可预测的方式发生变化。可以理解为:将多个组件共享的变量全部存储在一个对象里面,然后将这个对象放在顶层的 Vue 实例中,让其他组件可以使用,它最大的特点是响应式。

一般情况下,我们会在 Vuex 中存放一些需要在多个界面中进行共享的信息。比如用户的登录状态、用户名称、头像、地理位置信息、商品的收藏、购物车中的物品等,这些状态信息,我们可以放在统一的地方,对它进行保存和管理。

Vuex 插件的安装

npm install --save vuex@3.6.2

注意版本问题:vue 的 2.x 版本对应 vuex 的 3.x 版本,vue 的 3.x 版本对应 vuex 的 4.x 版本

在 src 目录下新建 store 文件夹,创建 index.js文件引入、安装、创建并导出Vuex对象。

import Vue from 'vue'
import Vuex from 'vuex'

//1.安装插件
Vue.use(Vuex)

//2.创建对象
const store = new Vuex.Store({
  state:{
    counter:1000
  },
  mutations:{

  },
  actions:{

  },
  getters:{

  },
  modules:{
    
  }
})
//3.导出使用
export default store

和 vue-router 的使用方式一样,在 main.js 文件中挂载使用

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

store 对象中存放的东西是固定的,主要有:state、mutations、actions、getters、modules

下图是官方给出的vuex状态管理图例

Vuex的基本使用

安装浏览器插件:devtools 方便调试 

state:存放需要共享的状态信息,使用时通过 $store.state.counter 即可拿到状态信息。

对 state 的状态信息进行修改:先拿到 store 对象,然后通过 commit 提交 mutations 中的方法。

使用 devtools 调试界面,可以跟踪查看每一次事件操作。 

 Vuex 核心概念

State:

单一状态树即单一数据源,在一个项目中只使用一个store对象,来存储所有共享的状态信息。

Getters:

类似于计算属性,在数据展示前进行一些变化处理,具有缓存功能,能够提高运行效率。eg:

  getters:{
    powerCounter(state){
      return state.counter * state.counter
    },
    more20stu(state){
      return state.students.filter(s => s.age > 20)
    },
    more20stuLength(state,getters){
      return getters.more20stu.length
    },
    moreAgeStu(state){
      return function(age){
        return state.students.filter(s => s.age > age)
      }
    }
  }

使用时,通过:$store.getters.powerCounter 获取:

    <h2>{{$store.getters.powerCounter}}</h2>
    <h2>{{$store.getters.more20stu}}</h2>
    <h2>{{$store.getters.more20stuLength}}</h2>
    <h2>{{$store.getters.moreAgeStu(18)}}</h2>

需要手动传参数时,可以在 getters 中返回一个 function:eg

    moreAgeStu(state){
      return function(age){
        return state.students.filter(s => s.age > age)
      }
    }

调用时传入参数即可: 

<h2>{{$store.getters.moreAgeStu(18)}}</h2>

Mutations:

store/index.js

  mutations:{//定义一些方法
    increment(state){
      state.counter++
    },
    decrement(state){
      state.counter--
    },
    incrementCount(state, payload){
      //1.普通提交方式
      //state.counter += count
      //2.特殊提交方式
      state.counter += payload.count
    },
    addStudent(state, obj){
      state.students.push(obj)
    }
  }

组件调用 :传递的参数(payload)可以是一个对象

<template>
  <div>
    <button @click="addCount(5)">+5</button>
    <button @click="addCount(10)">+10</button>
    <button @click="addStudent({id:105, name:'name6', age:29})">添加学生</button>
  </div>
</template>

<script>
export default {
  name:"HelloVuex",
  methods:{
    addCount(count){
      //1.普通的提交风格
      // this.$store.commit('incrementCount',count)
      //2.特殊的提交风格
      this.$store.commit({
        type:'incrementCount',
        count:count
      })
    },
    addStudent(stu){
      this.$store.commit('addStudent',stu)
    }
  }
}
</script>

<style>

</style>

 mutations在处理异步操作时,能够引起页面的响应式变化,但是 devtools 无法进行监听。

 比如:在 mutations 中执行以下代码

    updateInfo(state){
      setTimeout(() => {
        state.info.name = 'James'
      }, 1000);
    }

Actions:

如果确实需要进行一些异步操作,比如网络请求,建议在 Actions 中进行处理,这样 devtools 就能够进行跟踪,由 Actions 处理异步操作,具体的函数部分仍交由 Mutations 进行处理。

  actions:{
    //context:上下文 === store
    aUpdateInfo(context,payload){
      setTimeout(() => {
        context.commit('updateInfo',payload)
        console.log(payload);
      }, 5000);
    }
  }

组件中使用时,调用:this.$store.dispatch('aUpdateInfo') 

    updateInfo(){
      // this.$store.commit('updateInfo')
      this.$store.dispatch('aUpdateInfo','参数')
    }

 结合Promise使用:

  actions:{
    //context:上下文 === store
    aUpdateInfo(context, payload){
      return new Promise((resolve, reject)=>{
        setTimeout(() => {
          context.commit('updateInfo');
          console.log(payload);
          resolve('11111')
        }, 1000);
      })
    }
  }
    updateInfo(){
      // this.$store.commit('updateInfo')
      this.$store
      .dispatch('aUpdateInfo','参数')
      .then(res =>{
        console.log('里面完成了提交');
        console.log(res);
      })
    }

Modules:

分模块管理数据

const moduleA = {
  state:{
    name: 'moduleA'
  },
  mutations:{
    updateName(state,payload){
      state.name = payload
    }
  },
  getters:{
    fullname(state){
      return state.name + '1111'
    },
    fullname2(state, getters){
      return getters.fullname + '2222'
    },
    fullname3(state, getters, rootState){
      //传入第三个参数:rootState为上一个store对象中的state
      return getters.fullname2 +rootState.counter
    }
  },
  actions:{
    aUpdateName(context){//context 中 的commit只指向该模块中的mutations
      setTimeout(() => {
        context.commit('updateName','xiaowang')
        console.log(context)
      },

const store = new Vuex.Store({
  state:{
    counter:1000,
    students:[
      {id:110, name: 'name1', age: 12},
      {id:111, name: 'name2', age: 21},
      {id:112, name: 'name3', age: 22},
      {id:113, name: 'name4', age: 20},
      {id:114, name: 'name5', age: 18}
    ],
    info:{
      name: 'kobe',
      age: 40,
      height: 1.89
    }
  },
  mutations:{//定义一些方法
    increment(state){
      state.counter++
    },
    decrement(state){
      state.counter--
    },
    incrementCount(state, payload){
      //1.普通提交方式
      //state.counter += count
      //2.特殊提交方式
      state.counter += payload.count
    },
    addStudent(state, obj){
      state.students.push(obj)
    },
    updateInfo(state){
      state.info.name = 'Jams'//响应式:事先定义过的为响应式
      // state.info['address'] = 'chengdu'//响应式
      // Vue.set(state.info,'address1','Asgin')//响应式
      // delete state.info.age//响应式
      // Vue.delete(state.info,'height')//响应式
    }
  },
  getters:{
    powerCounter(state){
      return state.counter * state.counter
    },
    more20stu(state){
      return state.students.filter(s => s.age > 20)
    },
    more20stuLength(state,getters){
      return getters.more20stu.length
    },
    moreAgeStu(state){
      return function(age){
        return state.students.filter(s => s.age > age)
      }
    }
  },
  actions:{
    //context:上下文 === store
    aUpdateInfo(context, payload){
      return new Promise((resolve, reject)=>{
        setTimeout(() => {
          context.commit('updateInfo');
          console.log(payload);
          resolve('11111')
        }, 1000);
      })
    }
  },
  modules:{
    a: moduleA
  }
})

组件中使用 :$store.state.a

    <h2>Modules中的内容</h2>
    <h2>{{$store.state.a.name}}</h2>
    <button @click="updateName">修改模块ModuleA中的名字</button>
    <h2>{{$store.getters.fullname3}}</h2>
    <button @click="aupdateName">actions修改name</button>

执行模块中的方法 :直接 $store.commit 提交,故 mutations 之间定义的方法名不能重复。

    updateName(){
      this.$store.commit('updateName','lisa')
    },
    aupdateName(){
      this.$store.dispatch('aUpdateName')
    }

打印出的 context 信息如下:

 包含根状态下的一些 state (rootState) 和 mutations (rootMutations)。 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Vuex ——详细介绍 的相关文章

随机推荐

  • matlab改进秃鹰算法IBES 可直接运行 包括23个测试函数 提供与原算法对比~Matlab

    文章目录 效果一览 文章概述 部分源码 参考资料 效果一览 文章概述 matlab改进秃鹰算法IBES 可直接运行 包括23个测试函数 提供与原算法对比 Matlab 部分源码 清空环境变量 warning off 关闭报警信息 close
  • 威联通qnap SMB速度慢 只有30M、50M的解决方法

    首先 保证NAS与电脑处于千兆以上的局域网中 其次 然后就没有然后了 mmp 研究了一晚上 客服一问三不知 补充一下 有可能这个方法改完无效 这时候你先把 限制匿名用户访问 选择启动 默认是启动严格 然后把否决文件再勾上 然后再取消掉 目前
  • GESP C++ 四级样题卷

    一 单选题 每题 2 分 共 30 分 1 在 C 中 指针变量的大小 单位 字节 是 A 2 B 4 C 8 D 与编译器有关 答案 D 解析 在大多数现代的 32 bit 和 64 bit 的 C 编译器中 指针变量的大小通常是 4 字
  • iOS进阶—Runtime源码解析:动态方法解析

    GitHub参考 PS 参考GitHub分享的objc runtime master代码 及Runtime003代码 iOS进阶 目录 接上文iOS进阶 Runtime源码解析 消息发送 查看Runtime源码 No implementat
  • JS 统计字符串

    function getLength val var str new String val var bytesCount 0 for var i 0 n str length i lt n i var c str charCodeAt i
  • 用watch监听this.$store数据的变化

    如监听this store state username的值 在watch对象中写 watch store state username 你需要执行的代码
  • ES版本升级后出现Trying to create too many scroll contexts. Must be less than or equal to: [500]异常

    从一个异常说起 I O dispatcher 79 WARN RestClient request POST http xx xx xxx xxx 8080 index search scroll 600s returned 1 warni
  • C++13-STL模板-栈stack

    C 13 STL模板 栈stack 在线练习 http noi openjudge cn https www luogu com cn 大纲要求 3 算法模板库中的函数 min max swap sort 4 栈 stack 队列 queu
  • 在线代理检测网站

    20210203 很久之前 写代理的代码的时候 记录过几个测试代理的网站 后来也就直接放在书签里吃灰了 这里直接把这个几个网站记录在这里 http www xdaili cn monitor http proxies site digger
  • C++封装篇 类对象的定义

    1 对象的实例化 在c 中类是一个模板 对象的实例化其实就是计算机根据一个类的设计制造出多个对象的过程 对象实例化有两种方式 从栈实例化 从堆实例化 2 从栈实例化 class TV public char name 20 电视机的铭牌 i
  • 完整的模糊推理系统介绍以及matlab中从零实现(下篇)

    模糊推理系统从零实现 在完整的模糊推理系统介绍以及matlab中从零实现 上篇 中 我们对一个完整的模糊推理系统所涉及到的知识点做了一个细致地展述 进而 我们可以根据实际需要设计一个属于自己的模糊推理系统 主要涉及到以下几个方面的参数设置
  • ARM架构介绍

    概览 Arm 架构为处 器或内核 称为处 单元PE 的设计提供了基础 Arm架构已经集成到许多片上系统 SoC 设备中 比如智能手机 微型计算机 嵌入式设备 服务器甚至超级计算机 Arm架构为软件开发人员提供了通用指令集和工作流程 也称为编
  • 电子技术基础(三)__第2章放大电路原理__英文简称

    静态分析 又称为直流分析 用于求出电路的直流工作状态 即l输入信号 一 先看几个英文符号 集电极及发射极间电压 简称管压降 发射结电压降 二 接着看 加上Q点的英文简称 Q点 放大电路的静态工作点 上述简称对应有 另外还有2个 这4个值 称
  • 一个简单的CUDA程序以及一些总结

    尝试些了自己第一个CUDA程序 结果问题果然很多 先把问题程序框架贴上来 这个程序是有错误的 include
  • 关于【Stable-Diffusion WEBUI】方方面面研究(内容索引)

    文章目录 零 前言 0 1 我的相关文章索引 0 2 本篇内容阅读提示 一 绘图 1 1 模型 1 2 绘图方式 文生图 1 3 插件 可选附加网络 LoRA插件 Additional networks 1 4 插件 ControlNet
  • pytest运用引进@pytest.mark.parametrize中ids 导致编码乱码解决

    pytest运用引进 pytest mark parametrize中ids 导致编码乱码解决 pytest mark parametrize 运行用例导致显示会形成乱码 有俩种方法解决 第一种 创建个pytest ini 文件 输入 py
  • 【华为OD机试】经典屏保【2023 B卷

    华为OD机试 真题 点这里 华为OD机试 真题考点分类 点这里 题目描述 DVD机在视频输出时 为了保护电视显像管 在待机状态会显示 屏保动画 如下图所示 DVD Logo在屏幕内来回运动 碰到边缘会反弹 请根据如下要求 实现屏保Logo坐
  • NGINX 传递客户端IP

    当服务部署在服务器上时 一般都是通过nginx做代理转发 但是在common中的aop日志打印时 ip获取到的就变成本地的了 可以通过修改nginx的代理配置 以及后端的工具类解析 打印真实ip nginx配置 只需配置在监听的对应端口下就
  • 决策树篇

    决策树 随机森林属于集成学习 Ensemble Learning 中的bagging算法 在集成学习中 主要分为bagging算法和boosting算法 我们先看看这两种方法的特点和区别 Bagging 套袋法 bagging的算法过程如下
  • Vuex ——详细介绍

    Vuex 是一个专门为 Vue js 应用程序开发的状态管理模式 它采用集中式存储管理应用的所有组件状态 并以相应的规则保证状态以一种可预测的方式发生变化 可以理解为 将多个组件共享的变量全部存储在一个对象里面 然后将这个对象放在顶层的 V