理解Vuex

news2024/10/6 18:26:14

Vuex是什么

专门在Vue中实现集中式状态(数据)管理的一个Vue插件,对Vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信

Vuex Github地址 

什么时候使用Vuex

多个组件依赖同一数据,来自不同组件行为需要变更同一数据

工作原理图

我们使用的是vue2,所以安装vuex命令为:npm i vuex@3

原因:就是导入的东西先执行完才会执行下面代码,解决方法:就是在store/index.js下使用Vue.use(Vuex) 

使用纯Vue编写

src/App.vue

<template>
    <div>
        <Count/>
    </div>
</template>

<script>
import Count from './components/Count'
export default {
    name: 'App',
    components: { Count },

}
</script>

src/components/Count.vue

<template>
  <div>
    <h1>当前求和为:{{ sum }}</h1>
    <select v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
    <button @click="incrementOdd">当前求和为奇数再加</button>
    <button @click="incrementWait">等一等再加</button>
  </div>
</template>

<script>
export default {
  name: 'Count',
  data(){
    return{
      sum:0,  //当前的和
      n:1     //用户选择的数字
    }
  },
  methods:{
    increment(){
      this.sum+=this.n
    },
    decrement(){
      this.sum-=this.n
    },
    incrementOdd(){
      if(this.sum%2)
        this.sum+=this.n
    },
    incrementWait(){
      setTimeout(()=>{
        this.sum+=this.n
      },500)
    }
  }
}
</script>

<style>
  button{
    margin-left: 5px;
  }
</style>

搭建Vuex环境

创建src/store/index.js该文件用于创建Vuex中最为核心的store

//引入vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// actions对象:用于响应组件中的动作
const actions={
    // context相当于精简版的$store
    jiaOdd(context,value){
        console.log('actions中的jiaOdd被调用了');
        if(context.state.sum%2){
            context.commit('JIA',value)
        }
    },
    jiaWait(context,value){
        console.log('actions中的jiaWait被调用了');
        setTimeout(()=>{
            context.commit('JIA',value)
        },500)
    }
}
// mutations对象:用于操作数据(state)
const mutations={
    JIA(state,value){
        console.log('mutations中的JIA被调用了');
        state.sum+=value
    },
    JIAN(state,value){
        console.log('mutations中的JIAN被调用了');
        state.sum-=value
    }
}
// state对象:用于存储数据
const state={
    sum:0   //当前的和
}
// 暴露/导出store
export default new Vuex.Store({
    actions,
    mutations,
    state
})

src/main.js中创建vm时传入store配置项

import Vue from 'vue'
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'

import store from './store'
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)

//创建vm
new Vue({
    el: '#app',
    render: h => h(App),
    store,
    beforeCreate(){
        Vue.prototype.$bus=this //安装全局事件总线
    }
})

Vuex的基本使用

记忆方法:客人进餐厅后,如果对菜品不熟悉的话,则需要叫服务员推荐,如果经常来的话,那么直接跳过服务员,直接跟后厨说菜就得了,dispatch相当于服务员,commit相当于后厨,state相当于菜品 

src/components/Count.vue 

<template>
  <div>
    <h1>当前求和为:{{ $store.state.sum }}</h1>
    <select v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
    <button @click="incrementOdd">当前求和为奇数再加</button>
    <button @click="incrementWait">等一等再加</button>
  </div>
</template>

<script>
export default {
  name: 'Count',
  data(){
    return{
      n:1     //用户选择的数字
    }
  },
  methods:{
    increment(){
      this.$store.commit('JIA',this.n)
    },
    decrement(){
      this.$store.commit('JIAN',this.n)
    },
    incrementOdd(){
      this.$store.dispatch('jiaOdd',this.n)
    },
    incrementWait(){
      this.$store.dispatch('jiaWait',this.n)
    }
  }
}
</script>

<style>
  button{
    margin-left: 5px;
  }
</style>

getters配置项

src/store/index.js

//引入vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// actions对象:用于响应组件中的动作
const actions={
    // context相当于精简版的$store
    jiaOdd(context,value){
        console.log('actions中的jiaOdd被调用了');
        if(context.state.sum%2){
            context.commit('JIA',value)
        }
    },
    jiaWait(context,value){
        console.log('actions中的jiaWait被调用了');
        setTimeout(()=>{
            context.commit('JIA',value)
        },500)
    }
}
// mutations对象:用于操作数据(state)
const mutations={
    JIA(state,value){
        console.log('mutations中的JIA被调用了');
        state.sum+=value
    },
    JIAN(state,value){
        console.log('mutations中的JIAN被调用了');
        state.sum-=value
    }
}
// state对象:用于存储数据
const state={
    sum:0,   //当前的和
    school:'黑马',
    subject:'前端'
}
//
const getters={
    bigSum(state){
        return state.sum*10
    }
}
// 暴露/导出store
export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})

四个map方法的使用

映射数据名称和从state当中数据名称两者相同才可以用数组写法

1.mapState方法:用于帮助映射State中的数据为计算属性

2.mapGetters方法:用于帮助映射getters中的数据为计算属性

3.mapMutations方法:用于帮助生成与mutations对话的方法

4.mapActions方法:用于帮助生成与actions对话的方法

<template>
  <div>
    <h1>当前求和为:{{ sum }}</h1>
    <h1>当前求和放大10倍为:{{ bigSum }}</h1>
    <h1>我在{{ school }},学习{{ subject }}</h1>
    <select v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="increment(n)">+</button>
    <button @click="decrement(n)">-</button>
    <button @click="incrementOdd(n)">当前求和为奇数再加</button>
    <button @click="incrementWait(n)">等一等再加</button>
  </div>
</template>

<script>
import {mapState,mapGetters,mapActions,mapMutations} from 'vuex'
export default {
  name: 'Count',
  data() {
    return {
      n: 1     //用户选择的数字
    }
  },
  computed:{
    // 对象写法1
    // ...mapState({sum:'sum',school:'school',subject:'subject'}),
    // 数组写法2
    ...mapState(['sum','school','subject']),
    // 值必须加单引号,如果没有加的话,会变成寻找变量
    // ...mapGetters({bigSum:'bigSum'})
    ...mapGetters(['bigSum'])
  },
  methods: {
    /* increment() {
      this.$store.commit('JIA', this.n)
    },
    decrement() {
      this.$store.commit('JIAN', this.n)
    },
    incrementOdd() {
      this.$store.dispatch('jiaOdd', this.n)
    },
    incrementWait() {
      this.$store.dispatch('jiaWait', this.n)
    } */

    ...mapMutations({increment:'JIA',decrement:'JIAN'}),
    // ...mapMutations(['JIA','JIAN']),

    ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    // ...mapActions('jiaOdd','jiaWait')
  }
}
</script>

<style>
button {
  margin-left: 5px;
}
</style>

注意:mapActions和mapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象event

多组件共享数据案例

src/components/Count.vue

<template>
  <div>
    <h1>当前求和为:{{ sum }}</h1>
    <h4 style="color:red">Person组件总人数为:{{ personList.length }}</h4>
    <h1>当前求和放大10倍为:{{ bigSum }}</h1>
    <h1>我在{{ school }},学习{{ subject }}</h1>
    <select v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="increment(n)">+</button>
    <button @click="decrement(n)">-</button>
    <button @click="incrementOdd(n)">当前求和为奇数再加</button>
    <button @click="incrementWait(n)">等一等再加</button>
  </div>
</template>

<script>
import {mapState,mapGetters,mapActions,mapMutations} from 'vuex'
export default {
  name: 'Count',
  data() {
    return {
      n: 1     //用户选择的数字
    }
  },
  computed:{
    ...mapState(['sum','school','subject','personList']),
    ...mapGetters(['bigSum'])
  },
  methods: {
    ...mapMutations({increment:'JIA',decrement:'JIAN'}),
    ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
  }
}
</script>

<style>
button {
  margin-left: 5px;
}
</style>

src/components/Person.vue

<template>
  <div>
    <h1>人员列表</h1>
    <h4 style="color: red;">Count组件求和为:{{ sum }}</h4>
    <input type="text" placeholder="请输入名字" v-model="name">
    <button @click="add">添加</button>
    <ul>
      <li v-for="p in personList" :key="p.id">{{ p.name }}</li>
    </ul>
  </div>
</template>

<script>
import { nanoid } from 'nanoid'
export default {
  name: 'Person',
  data() {
    return {
      name: ''
    }
  },
  computed: {
    personList() {
      return this.$store.state.personList
    },
    sum() {
      return this.$store.state.sum
    }
  },
  methods: {
    add() {
      if (this.name === '') return
      const personObj = { id: nanoid(), name: this.name }
      // console.log(personObj)
      this.$store.commit('ADD_PERSON', personObj)
      this.name = ''
    }
  }
}
</script>

src/App.vue

<template>
    <div>
        <Count/>
        <hr>
        <Person/>
    </div>
</template>

<script>
import Count from './components/Count'
import Person from './components/Person'
export default {
    name: 'App',
    components: { Count,Person },

}
</script>

src/store/index.js

//引入vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// actions对象:用于响应组件中的动作
const actions={
    // context相当于精简版的$store
    jiaOdd(context,value){
        console.log('actions中的jiaOdd被调用了');
        if(context.state.sum%2){
            context.commit('JIA',value)
        }
    },
    jiaWait(context,value){
        console.log('actions中的jiaWait被调用了');
        setTimeout(()=>{
            context.commit('JIA',value)
        },500)
    }
}
// mutations对象:用于操作数据(state)
const mutations={
    JIA(state,value){
        console.log('mutations中的JIA被调用了');
        state.sum+=value
    },
    JIAN(state,value){
        console.log('mutations中的JIAN被调用了');
        state.sum-=value
    },
    ADD_PERSON(state,value){
        console.log('mutations中的JIAN被调用了');
        state.personList.unshift(value)
    }
}
// state对象:用于存储数据
const state={
    sum:0,   //当前的和
    school:'黑马',
    subject:'前端',
    personList:[
        {id:'001',name:'张三'}
    ]
}
//
const getters={
    bigSum(state){
        return state.sum*10
    }
}
// 暴露/导出store
export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})

src/main.js

import Vue from 'vue'
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'

import store from './store'
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)

//创建vm
new Vue({
    el: '#app',
    render: h => h(App),
    store,
    beforeCreate(){
        Vue.prototype.$bus=this //安装全局事件总线
    }
})

 

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

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

相关文章

走向具身智能丨美格高算力AI模组 以端侧智慧连接人和家庭

“贾维斯&#xff0c;我需要你的帮助。”这是钢铁侠Tony Stark在电影中向他的人工智能助手Jarvis寻求支持的场景。《钢铁侠》中的贾维斯不仅令观众着迷&#xff0c;也点燃了人们对于智能助手的想象力。正如电影《她》中所描绘的那样&#xff0c;智能助手还可以与人类建立真实的…

dolphinscheduler伪分布式安装

1、上传安装包 2、安装 #解压 重命名 [rootdatacollection conf]# cd /opt/modules/ [rootdatacollection modules]# tar -zxf apache-dolphinscheduler-2.0.6-bin.tar.gz -C /opt/installs/ [rootdatacollection modules]# cd ../installs/ [rootdatacollection installs]# m…

这8种算法——程序员必会

一个程序员一生中可能会邂逅各种各样的算法&#xff0c;但总有那么几种&#xff0c;是作为一个程序员一定会遇见且大概率需要掌握的算法。今天就来聊聊这些十分重要的“必抓&#xff01;”算法吧~ 算法一&#xff1a;快速排序法 快速排序法是对冒泡排序的一种改进&#xff0c…

Jmeter测试脚本编写详解(配详图)

一、简介 Apache JMeter是Apache组织开发的基于Java的压力测试工具。用于对软件做压力测试&#xff0c;它最初被设计用于Web应用测试&#xff0c;但后来扩展到其他测试领域。 它可以用于测试静态和动态资源&#xff0c;例如静态文件、Java 小服务程序、CGI 脚本、Java 对象、数…

ORACLE数据库scott没有相关权限

1. 首先登陆具有DBA权限的用户 1.1 打开cmd 1.2 输入以下命令 sqlplus / as sysdab上述命令中的 / as sysdba 表示使用操作系统认证登录&#xff0c;同时指定DBA权限 1.3 回车执行命令&#xff0c;系统或将提示输入密码&#xff08;没有则直接跳过&#xff09; 1.4 密码正…

AndroidStudio-实现登录界面(数据存储在SQLite)

要求&#xff1a;每种错误信息采用Toast进行提示 &#xff08;1&#xff09;未注册的用户不能进行登录&#xff1b; &#xff08;2&#xff09;用户名和密码不能为空&#xff1b; &#xff08;3&#xff09;用户名不能重复&#xff1b; 一、创建新工程 点击next 修改名字 &…

JQuery 实现点击按钮添加及删除 input 框

前言 用于记录开发中常用到的&#xff0c;快捷开发 需求新增功能 比如说&#xff0c;我台设备可以设置一个或多个秘钥&#xff0c;有时候我配置一个秘钥时&#xff0c;就不需要多个输入框&#xff0c;当我想配置多个秘钥时&#xff0c;就需要添加多个输入框。 实现 HTML …

Adobe打印机另存pdf出错生成log文件,打印失败

目录预览 一、问题描述二、原因分析三、解决方案四、参考链接 一、问题描述 用adobe打印机转pdf出错生成log文件,打印失败&#xff0c;log文件内容如下&#xff1a; %%[ ProductName: Distiller ]%% FZXBSJW--GB1-0 not found, using Courier. %%[ Error: typecheck; Offendi…

Mac安装MySQL详细教程

1、MySQL安装包下载 还没下载的话请前往官网下载 我们可以看到这里有两个不同架构的dmg的安装包&#xff0c;如果不知道自己电脑是ARM还是X86的话可以打开终端输入&#xff1a;uname -a 或者 uname -a | awk -F " " {print $(NF-1)} 来查看如下图&#xff1a; 这里显…

v-cloak和v-once和v-pre指令

v-cloak指令&#xff08;没有值&#xff09;&#xff1a; 1.本质是一个特殊属性&#xff0c;Vue实例创建完毕并接管容器后&#xff0c;会删掉v-cloak属性。 2.使用css配合v-cloak可以解决网速慢时页面展示出{{xxx}}的问题 v-once: v-once指令&#xff1a; 1.v-once所在节点在初…

基于linux下的高并发服务器开发(第一章)- Linux开发环境搭建

​​​​​​基于linux下的高并发服务器开发&#xff08;第一章&#xff09;-Linux环境开发搭建1.1_呵呵哒(&#xffe3;▽&#xffe3;)"的博客-CSDN博客https://blog.csdn.net/weixin_41987016/article/details/131681333?spm1001.2014.3001.5501 解决Ubuntu 虚拟机没…

高数笔记01:函数、极限、连续

图源&#xff1a;文心一言 本文是我学习高等数学第一章的一些笔记和心得&#xff0c;主要介绍了函数、极限、连续这三个基本概念&#xff0c;以及它们的性质和很基础的计算技巧。希望可以与考研路上的小伙伴一起努力上岸~~&#x1f95d;&#x1f95d; 第1版&#xff1a;查资料…

Python自动化测试之cookie绕过登录(保持登录状态)

前言 在编写接口自动化测试用例或其他脚本的过程中&#xff0c;经常会遇到需要绕过用户名/密码或验证码登录&#xff0c;去请求接口的情况&#xff0c;一是因为有时验证码会比较复杂&#xff0c;比如有些图形验证码&#xff0c;难以通过接口的方式去处理&#xff1b;再者&…

系统学习Halcon视觉软件指南

要系统学习Halcon视觉软件&#xff0c;您可以按照以下步骤进行&#xff1a; 我这里刚好有嵌入式、单片机、plc的资料需要可以私我或在评论区扣个6 学习基本概念&#xff1a;了解Halcon的基本概念和术语&#xff0c;例如图像处理、特征提取、图像匹配等。可以查阅Halcon的官方…

Web开发的富文本编辑器CKEditor介绍,Django有库ckeditor_uploader对它进行支持,django-ckeditor安装方法及使用注意事项

当需要在网页应用程序中提供富文本编辑功能时&#xff0c;CKEditor是一个流行的选择。CKEditor是一个开源的JavaScript富文本编辑器&#xff0c;它提供了强大的功能和用户友好的界面&#xff0c;使用户可以轻松创建和编辑格式化的文本内容。 以下是CKEditor的一些主要特性&…

MySQL进阶:函数

​ 在MySQL中&#xff0c;为了提高代码重用性和隐藏实现细节&#xff0c;MySQL提供了很多函数。函数可以理解为别人封装好的模板代码。 一、聚合函数 ​ 在MySQL中&#xff0c;聚合函数主要由&#xff1a;count、sum、min、max、avg组成&#xff0c;这些函数前面已经提过&…

std::stox类型

std::stod 函数原型 double stod (const string& str, size_t* idx 0); double stod (const wstring& str, size_t* idx 0);函数功能 将std::string字符串转化为双精度类型 函数参数 str 待转换的字符串 idx 如果idx的指针不为空&#xff0c;则该函数会将idx的…

为什么计算ORB特征点的时候还要取圆形而不是方形像素区域呢?

ORB (Oriented FAST and Rotated BRIEF)是一种在计算机视觉中广泛应用的特征检测和描述符算法。它的设计目的是为了快速、有效地提取图像中的关键点和描述符。在ORB的过程中&#xff0c;确实会涉及到提取圆形区域的操作&#xff0c;这主要出于以下的原因&#xff1a; 旋转不变性…

C++ VS 链接第三方库

C VS 链接第三方库 include lib dll 需要把动态库考到可执行程序的目录之下

客户异常数据清洗详细教程——pandas

前言 在不同行业中&#xff0c;我们经常会遇到一个麻烦的问题&#xff1a;数据清洗。尤其是当我们需要处理客户编码异常数据时&#xff0c;这个问题变得尤为重要。想象一下&#xff0c;许多银行都是以客户为单位管理数据的&#xff0c;因此每个客户都有一个独特的编码。在处理…