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


    一、导言

    1、引言

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

    2、vuex核心概念

    Vuex分成五个部分:

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

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

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

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

    5. 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文件中新建vuexstore实例,并注册上面引入的各大模块

    1. import Vue from 'vue'
    2. import Vuex from 'vuex'
    3. import state from './state'
    4. import getters from './getters'
    5. import actions from './actions'
    6. import mutations from './mutations'
    7. Vue.use(Vuex)
    8. const store = new Vuex.Store({
    9.         state,
    10.         getters,
    11.         actions,
    12.         mutations
    13. })
    14. export default store

     

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

     

    1. // The Vue build version to load with the `import` command
    2. // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
    3. import Vue from 'vue'
    4. //开发环境下才会引入mockjs
    5. // process.env.MOCK && require('@/mock')
    6. // 新添加1
    7. import ElementUI from 'element-ui'
    8. // 新添加2,避免后期打包样式不同,要放在import App from './App';之前
    9. import 'element-ui/lib/theme-chalk/index.css'
    10. import App from './App'
    11. import router from './router'
    12. import store from './store'
    13. // 新添加3----实例进行一个挂载
    14. Vue.use(ElementUI)
    15. Vue.config.productionTip = false
    16. import axios from '@/api/http'
    17. import VueAxios from 'vue-axios'
    18. Vue.use(VueAxios, axios)
    19. /* eslint-disable no-new */
    20. new Vue({
    21. el: '#app',
    22. router,
    23. store,
    24. //定义变量
    25. data() {
    26. return {
    27. Bus: new Vue()
    28. }
    29. },
    30. components: {App},
    31. template: ''
    32. })

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

    二、取值存值

    1、前期准备

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

    state.js

    1. export default {
    2. stateName:'王德法'
    3. }

    mutations.js

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

    getters.js

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

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

    index.js

    1. import Vue from 'vue'
    2. import Vuex from 'vuex'
    3. import state from './state'
    4. import getters from './getters'
    5. import actions from './actions'
    6. import mutations from './mutations'
    7. Vue.use(Vuex)
    8. const store = new Vuex.Store({
    9. state,
    10. getters,
    11. actions,
    12. mutations
    13. })
    14. export default store

    2、取值

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

    1. <template>
    2. <div>
    3. <h2>页面一h2>
    4. <button @click="in1">获取state值button>
    5. div>
    6. template>
    7. <script>
    8. export default {
    9. data() {
    10. return {
    11. msg: '页面一默认值'
    12. }
    13. },
    14. methods: {
    15. in1() {
    16. let stateName = this.$store.state.stateName;
    17. alert(stateName)
    18. }
    19. }
    20. }
    21. script>
    22. <style scoped>
    23. style>

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

    3、存值

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

    1. <template>
    2. <div>
    3. <h2>页面一h2>
    4. 请输入内容:<input v-model="msg"/>
    5. <button @click="in1">获取state值button>
    6. <button @click="in2">改变state值button>
    7. div>
    8. template>
    9. <script>
    10. export default {
    11. data() {
    12. return {
    13. msg: '页面一默认值'
    14. }
    15. },
    16. methods: {
    17. in1() {
    18. let stateName = this.$store.state.stateName;
    19. alert(stateName)
    20. },
    21. in2() {
    22. this.$store.commit('setName', {
    23. stateName: this.msg
    24. })
    25. }
    26. }
    27. }
    28. script>
    29. <style scoped>
    30. style>

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

    1. <template>
    2. <div>
    3. <h2>页面二h2>
    4. {{ msg }}
    5. {{ updName}}
    6. div>
    7. template>
    8. <script>
    9. export default {
    10. data() {
    11. return {
    12. msg: '页面二默认值'
    13. }
    14. },
    15. computed: {
    16. updName() {
    17. // return this.$store.state.stateName;
    18. return this.$store.getters.getName;
    19. }
    20. }
    21. }
    22. script>
    23. <style scoped>
    24. style>

    三、异步加载

    1、什么是异步请求

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

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

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

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

    2、前端异步

    actions.js里面写入方法

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

    在页面里面写入事件

    1. <template>
    2. <div>
    3. <h2>页面一h2>
    4. 请输入内容:<input v-model="msg"/>
    5. <button @click="ind">异步改变值button>
    6. div>
    7. template>
    8. <script>
    9. export default {
    10. data() {
    11. return {
    12. msg: '页面一默认值'
    13. }
    14. },
    15. methods: {
    16. ind() {
    17. // setNameAsync setNameAjax
    18. this.$store.dispatch('setNameAsync', {
    19. stateName: this.msg,
    20. _this:this
    21. })
    22. }
    23. }
    24. }
    25. script>
    26. <style scoped>
    27. style>

    3、ajax请求

    页面

    1. <template>
    2. <div>
    3. <h2>页面一h2>
    4. 请输入内容:<input v-model="msg"/>
    5. <button @click="ind">异步改变值button>
    6. div>
    7. template>
    8. <script>
    9. export default {
    10. data() {
    11. return {
    12. msg: '页面一默认值'
    13. }
    14. },
    15. methods: {
    16. ind() {
    17. this.$store.dispatch('setNameAjax', {
    18. stateName: this.msg,
    19. _this:this
    20. })
    21. }
    22. }
    23. }
    24. script>
    25. <style scoped>
    26. style>

    actions.js

    1. export default {
    2. // 利用ajax请求;context == vue的上下文
    3. setNameAjax: (context, payload) => {
    4. let _this = payload._this;
    5. let url = _this.axios.urls.VUEX_AJAX;
    6. let params = {
    7. resturantName: payload.stateName
    8. }
    9. _this.axios.post(url, params).then(r => {
    10. console.log(r);
    11. }).catch(e => {
    12. });
    13. }
    14. }

    后端方法

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

  • 相关阅读:
    《数字图像处理-OpenCV/Python》连载(7)视频文件的读取与保存
    11.13 训练周记
    Scala入门到放弃—02—函数
    Ajax学习笔记第8天
    BIM如何算量?以及工作流程是怎么样?
    使用VoIP网关的5种不同场景
    神经网络中的基本结构--卷积层和最大池化
    BreederDAO 第一项提案发布:DAO 组织的宪法章程
    flask——数据库连接池、wtfroms、信号、多app应用、flask-script
    WSL2-ubuntu18.04配置笔记 :6Rstudioserver配置
  • 原文地址:https://blog.csdn.net/weixin_74383330/article/details/133743000