【Vuex+ElementUI】Vuex中取值存值以及异步加载的使用

news/2025/2/14 7:58:20/

一、导言

1、引言

    Vuex是一个用于Vue.js应用程序的状态管理模式和库。它建立在Vue.js的响应式系统之上,提供了一种集中管理应用程序状态的方式。使用Vuex,您可以将应用程序的状态存储在一个单一的位置(即“存储”)中,并且通过使用可预测的方式来修改它(即“提交”和“派遣”更改)。

2、vuex核心概念

Vuex分成五个部分:

State(状态):存储应用程序的状态,可以通过一个单一的对象来表示。(单一状态树)

Mutations(变化):修改状态的唯一方法。每个mutation都是一个事件,包含一个类型和一个处理函数,用于实际修改状态。(状态获取)

Actions(动作):类似于mutations,但可以包含异步操作。Action提交mutation来修改状态,而不是直接修改。(触发同步事件)

Getters(获取器):用于从存储中获取派生状态。相当于Vue组件中的计算属性。(提交mutation,可以包含异步操作)

Module:将vuex进行分模块

3. vuex使用步骤

  3.1、安装

      npm install vuex -S

      npm i -S vuex@3.6.2

   3.2、创建store模块,分别维护state/actions/mutations/getters

      store

        state.js

        actions.js

        mutations.js

        getters.js

再使用index.js把四个js文件包裹起来

   3.3、在store/index.js文件中新建vuex的store实例,并注册上面引入的各大模块

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
const store = new Vuex.Store({state,getters,actions,mutations})export default store

 3.4、在main.js中导入并使用store实例

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
//开发环境下才会引入mockjs
// process.env.MOCK && require('@/mock')
// 新添加1
import ElementUI from 'element-ui'
// 新添加2,避免后期打包样式不同,要放在import App from './App';之前
import 'element-ui/lib/theme-chalk/index.css'import App from './App'
import router from './router'
import store from './store'// 新添加3----实例进行一个挂载
Vue.use(ElementUI)
Vue.config.productionTip = falseimport axios from '@/api/http'
import VueAxios from 'vue-axios'Vue.use(VueAxios, axios)/* eslint-disable no-new */
new Vue({el: '#app',router,store,//定义变量data() {return {Bus: new Vue()}},components: {App},template: '<App/>'
})

  最后进行编码,就可以使用vuex的相关功能

 

二、取值存值

1、前期准备

再创建好在store里面的js文件里面进行操作

state.js

export default {stateName:'王德法'
}

 mutations.js

export default {// state == state.js文件中导出的对象;payload是vue文件传过来的参数setName: (state, payload) => {state.stateName = payload.stateName}
}

 getters.js

export default {// state == state.js文件中导出的对象;payload是vue文件传过来的参数getName: (state) => {return state.stateName;}
}

 最后在index.js里面配置好文件

 index.js

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'Vue.use(Vuex)const store = new Vuex.Store({state,getters,actions,mutations
})export default store

 2、取值

在写好的页面进行操作的取值

<template><div><h2>页面一</h2><button @click="in1">获取state值</button></div>
</template>
<script>
export default {data() {return {msg: '页面一默认值'}},methods: {in1() {let stateName = this.$store.state.stateName;alert(stateName)}}
}
</script><style scoped></style>

在取值的this.$store.state.stateName我们不是推荐的,我们推荐使用this.$store.getters.getName,效果是一样的

3、存值

在取值的基础上加上存值的方法

<template><div><h2>页面一</h2>请输入内容:<input v-model="msg"/><button @click="in1">获取state值</button><button @click="in2">改变state值</button></div>
</template>
<script>
export default {data() {return {msg: '页面一默认值'}},methods: {in1() {let stateName = this.$store.state.stateName;alert(stateName)},in2() {this.$store.commit('setName', {stateName: this.msg})}}
}
</script><style scoped></style>

我们也可以使用第二个页面进行存取值

<template><div><h2>页面二</h2>{{ msg }}{{ updName}}</div>
</template>
<script>
export default {data() {return {msg: '页面二默认值'}},computed: {updName() {// return this.$store.state.stateName;return this.$store.getters.getName;}}
}
</script><style scoped></style>

 

 

 三、异步加载

1、什么是异步请求

     在Vuex中,异步请求通常是指通过网络发送的异步操作,例如从服务器获取数据或向服务器发送数据。

        在Vuex中,可以使用异步操作来更新存储在状态库中的数据。常见的异步请求包括使用Ajax、axios等库发送HTTP请求,或者使用WebSocket进行实时通信。

        通过这些概念的配合,可以在Vuex中处理异步请求,并将响应的数据保存到状态库中,以便在应用程序中使用。

Actions(动作):Actions是Vuex中用于触发异步请求并提交mutation的地方。通过定义actions来描述应用程序中的各种操作,如从服务器获取数据、异步更新状态等。在actions中可以使用异步代码,并在需要时通过commit方法提交mutation来更新状态。
Mutations(变化):Mutations是Vuex中用于修改状态的地方。异步请求通常是在actions中进行的,当异步操作完成后,actions会调用commit方法来触发对应的mutation,从而修改状态。
Getters(获取器):Getters是Vuex中用于从状态中获取数据的地方。可以在getters中定义一些计算属性,通过对状态进行处理和过滤,从而得到所需的数据。

 2、前端异步

actions.js里面写入方法

export default {// context == vue的上下文;payload是vue文件传过来的参数setNameAsync: (context, payload) => {//5秒后调用调方法setTimeout(function () {context.commit('setName', payload)}, 5000)}
}

在页面里面写入事件

<template><div><h2>页面一</h2>请输入内容:<input v-model="msg"/><button @click="ind">异步改变值</button></div>
</template>
<script>
export default {data() {return {msg: '页面一默认值'}},methods: {ind() {// setNameAsync setNameAjaxthis.$store.dispatch('setNameAsync', {stateName: this.msg,_this:this})}}
}
</script><style scoped></style>

 3、ajax请求

页面

<template><div><h2>页面一</h2>请输入内容:<input v-model="msg"/><button @click="ind">异步改变值</button></div>
</template>
<script>
export default {data() {return {msg: '页面一默认值'}},methods: {ind() {this.$store.dispatch('setNameAjax', {stateName: this.msg,_this:this})}}
}
</script><style scoped></style>

actions.js

export default {// 利用ajax请求;context == vue的上下文setNameAjax: (context, payload) => {let _this = payload._this;let url = _this.axios.urls.VUEX_AJAX;let params = {resturantName: payload.stateName}_this.axios.post(url, params).then(r => {console.log(r);}).catch(e => {});}
}

后端方法

 public JsonResponseBody<?> queryVuex(HttpServletRequest request) {String resturantName = request.getParameter("resturantName");SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String date = sdf.format(new Date());try {System.out.println("模拟异步情况,睡眠6秒,不能超过10秒,axios超时时间设置的是10秒!");Thread.sleep(6000);System.out.println("睡醒了,继续...");} catch (Exception e) {e.printStackTrace();}return new JsonResponseBody<>(resturantName + "-" + date,true,0,null);}


http://www.ppmy.cn/news/1148523.html

相关文章

搞流式计算,大厂也没有什么神话

抖音、今日头条&#xff0c;是字节跳动旗下最受用户欢迎的两款产品&#xff0c;也是字节跳动的门面。而在这背后&#xff0c;是众多技术团队在支撑&#xff0c;流式计算就是其中一支。 不过&#xff0c;即使是在字节跳动&#xff0c;搞流式计算也没有神话。只有一群年轻人&…

安装Docker(Linux:CentOS)

大家好我是苏麟今安装一下Docker. 安装Docker Docker 分为 CE 和 EE 两大版本。CE 即社区版&#xff08;免费&#xff0c;支持周期 7 个月&#xff09;&#xff0c;EE 即企业版&#xff0c;强调安全&#xff0c;付费使用&#xff0c;支持周期 24 个月。 Docker CE 分为 stab…

Talk | ACL‘23 杰出论文,MultiIntruct:通过多模态指令集微调提升VLM的零样本学习

本期为TechBeat人工智能社区第536期线上Talk&#xff01; 北京时间10月11日(周三)20:00&#xff0c;弗吉尼亚理工大学博士生—徐智阳、沈莹的Talk已准时在TechBeat人工智能社区开播&#xff01; 他们与大家分享的主题是: “通过多模态指令集微调提升VLM的零样本学习”&#xff…

保护互联网数据安全:关键方法与最佳实践

在当今数字化时代&#xff0c;互联网数据安全已经成为个人、企业和组织的首要任务之一。随着信息技术的迅猛发展&#xff0c;网络威胁也不断演进&#xff0c;因此保护互联网数据安全变得尤为关键。本文将介绍一些关键方法和最佳实践&#xff0c;帮助您确保互联网数据的安全性。…

201、RabbitMQ 之 Exchange 典型应用模型 之 工作队列(Work Queue)

目录 ★ 工作队列介绍代码演示测试注意点1&#xff1a;注意点2&#xff1a; ★ 工作队列介绍 工作队列&#xff1a; 就是让多个消费者竞争消费同一个消息队列的消息&#xff0c;相当于多个消费者共享消息队列。 ▲ RabbitMQ可以让多个消费者竞争消费同一个消息队列 ▲ 消息队…

基于PTP的同步时钟同步

基于PTP的同步时钟同步 编辑搜图 请点击输入图片描述&#xff08;最多18字&#xff09; ​本设计采用PTP (Precision Time Protocol)协议&#xff0c;来实现同步时间。PTP是一种精确测量和控制系统的网络协议&#xff0c;用于同步分布式系统中的各种设备和服务器的时间。 首先…

生产级Stable Diffusion AI服务部署指南【BentoML】

在本文中&#xff0c;我们将完成 BentoML 和 Diffusers 库之间的集成过程。 通过使用 Stable Diffusion 2.0 作为案例研究&#xff0c;你可以了解如何构建和部署生产就绪的 Stable Diffusion 服务。 推荐&#xff1a;用 NSDT编辑器 快速搭建可编程3D场景 Stable Diffusion 2.0 …

实战指南:使用 kube-prometheus-stack 监控 K3s 集群

作者简介 王海龙&#xff0c;Rancher 中国社区技术经理&#xff0c;Linux Foundation APAC Evangelist&#xff0c;负责 Rancher 中国技术社区的维护和运营。拥有 9 年的云计算领域经验&#xff0c;经历了 OpenStack 到 Kubernetes 的技术变革&#xff0c;无论底层操作系统 Lin…