vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vuex存值取值与异步请求

Vuex存值取值与异步请求处理方式

作者:孤留光乩

本文将详细介绍Vuex的使用方法,包括参数值的获取、修改,以及异步数据处理,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

前言

在大型的Vue.js应用中,我们经常需要共享状态和进行复杂的状态管理。

Vuex是一个专为Vue.js设计的状态管理库,提供了一种集中式的方式来管理应用的所有组件的状态。

一、Vuex简介

1.Vuex是什么

Vuex是一个专为Vue.js应用设计的状态管理库。它提供了一种集中式的方式来管理应用的所有组件的状态,并且使得状态的变化变得可追踪、可维护。通过使用Vuex,我们可以将共享的数据以及与数据相关的逻辑统一管理,从而提高代码的可读性和可维护性。

在Vue.js应用中,组件之间的通信可以通过props和事件来实现。然而,当应用规模较大时,组件之间的状态交互变得更加复杂,而这些状态往往需要在多个组件之间共享和同步。这时,使用Vuex可以让我们更好地解决这些问题。

2.Vuex的核心概念

3.使用Vuex的好处

4.Vuex执行流程

二、Vuex的使用步骤

1.安装Vuex

 npm i -S vuex@3.6.2

在package.json中可以看到Vuex

2.创建store模块,分别维护state/actions/mutations/getters

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

3.使用Vuex存储值,获取值和改变值

1.state.js---存值

export default{
  name:'美猴王'
}

2.mutations.js---改变值

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

3.getters.js---取值

export default{
  getName:(state)=>{
    //state指的是state.js文件中导出的对象
    return state.name;
  }
}

4.store/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

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

6.在views下创建vuex目录并创建One.vue组件

<template>
  <div>
    <h1>我是number one</h1>

     猴名:<input v-model="msg"/>
        <button @click="fun1">获取vuex的值</button>
        <button @click="fun2">改变vuex的值</button>

  </div>
</template>

<script>
  export default{
    data(){
      return{
        msg:'吉吉'
      }
    },
    methods: {
          fun1(){
           let name= this.$store.state.name;
           alert(name)
          },
          fun2(){
            this.$store.commit('setName',{
              name:this.msg
            })
          }
        }
  }
</script>

<style>
</style>

效果演示

7.跨页面获取值

<template>
  <div>
    <h1>我是number Two</h1>
    {{name}}
  </div>
</template>

<script>
  export default {
    computed:{
      name(){
        // return this.$store.state.name;
        return this.$store.getters.getName;
      }
    }
  }
</script>

<style>
</style>

注:

效果演示

4.通过异步实现获取和改变值

action.js:异步改变值

export default {
  setNameSynac:(context,payload) => {
    //context指的是vuex的上下文
    setTimeout(function(){
      context.commit('setName',payload)
    },6000)
}
};

One.vue组件

<template>
  <div>
    <h1>我是number one</h1>

    猴名:<input v-model="msg" />
    <button @click="fun1">获取vuex的值</button>
    <button @click="fun2">改变vuex的值</button>
    <button @click="fun3">异步改变vuex的值</button>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        msg: '吉吉'
      }
    },
    methods: {
      fun1() {
        let name = this.$store.state.name;
        alert(name)
      },
      fun2() {
        this.$store.commit('setName', {
          name: this.msg
        })
      },
      fun3() {
        this.$store.dispatch('setNameSynac', {
          name: this.msg
        })
      }
    }
  }
</script>

<style>
</style>

效果演示

5.通过异步实现发送Ajax到后端请求

后端代码

package com.ctb.ssm.controller;

import com.ctb.ssm.util.JsonResponseBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/vuex")
public class VuexController {

    @RequestMapping("/queryVuex")
    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("模拟异步情况,睡眠5秒,不能超过10秒,axios超时时间设置的是10秒!");
            Thread.sleep(5000);
            System.out.println("睡醒了,继续...");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResponseBody<>(resturantName + "-" + date,true,0,null);
    }
}

src/api/action.js配置后端请求

 'VUEX': '/vuex/queryVuex', //Vuex后端异步获取

src/store/action.js异步发送Ajax请求到后端

setNameAjax: (context, payload) => {
    let _this=payload._this
    let url = _this.axios.urls.VUEX
    let params = {
      resturantName: payload.name
    }
    _this.axios.post(url, params).then(r => {
    console.log(r)

    }).catch(r => {

    });
    }

One.vue组件

<template>
  <div>
    <h1>我是number one</h1>

    猴名:<input v-model="msg" />
    <button @click="fun1">获取vuex的值</button>
    <button @click="fun2">改变vuex的值</button>
    <button @click="fun3">异步改变vuex的值</button>
    <button @click="fun4">异步发送Ajax请求到后端</button>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        msg: '吉吉'
      }
    },
    methods: {
      fun1() {
        let name = this.$store.state.name;
        alert(name)
      },
      fun2() {
        this.$store.commit('setName', {
          name: this.msg
        })
      },
      fun3() {
        this.$store.dispatch('setNameSynac', {
          name: this.msg
        })
      },
      fun4() {
        this.$store.dispatch('setNameAjax', {
          name: this.msg,
          _this: this
        })
      }

    }
  }
</script>

<style>
</style>

效果演示

注:

1.在store/action.js中this并不代表vue实例,所以我们需在vue组件中将this传递过去

2.异步相应时间超时内容不会显示,我们可以尽量避免时间过长或者可以修改响应后端超时的时间。

6.同步和异步的区别

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文