[Vuex+ElementUI] The use of value retrieval, storage and asynchronous loading in Vuex

1. Introduction

1 Introduction

        Vuex is a state management pattern and library for Vue.js applications. It is built on the reactive system of Vue.js and provides a centralized way to manage application state. With Vuex, you can store the state of your application in a single location (i.e. "storage") and modify it in a predictable way (i.e. "commit" and "dispatch" changes).

2. vuex core concepts

Vuex is divided into five parts:

  1. State : Stores the state of the application, which can be represented by a single object. (Single state tree)

  2. Mutations : The only way to modify state. Each mutation is an event, containing a type and a handler function, which is used to actually modify the state. (status acquisition)

  3. Actions : Similar to mutations, but can contain asynchronous operations. Action submits mutations to modify the state, rather than modifying it directly. (Trigger sync event)

  4. Getters : used to get derived state from storage. Equivalent to computed properties in Vue components. (Submit mutation, which can include asynchronous operations)

  5. Module : Divide vuex into modules

3. vuex usage steps

  3.1. Installation

      npm install vuex -S

      npm and -S [email protected]

  3.2. Create a store module and maintain state/actions/mutations/getters respectively.

      store

        state.js

        actions.js

        mutations.js

        getters.js

Then use index.js to wrap the four js files

  

  3.3. Create a new vuex store instance in the store/index.js file and register the major modules introduced above.

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. Import and use the store instance in main.js

 

// 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 = false

import 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/>'
})

 Finally, after coding, you can use the related functions of vuex

2. Get value and store value

1. Preliminary preparation

Then create it and operate it in the js file in the store.

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;
  }
}

Finally, configure the file in 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. Value

The value of performing operations on the written page

<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>

We do not recommend the value of this.$store.state.stateName . We recommend using this.$store.getters.getName . The effect is the same.

3. Store value

On the basis of obtaining the value, add the method of storing the value

<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>

We can also use the second page to access values

<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>

3. Asynchronous loading

1. What is an asynchronous request?

        In Vuex, an asynchronous request usually refers to an asynchronous operation sent over the network, such as getting data from or sending data to a server.

        In Vuex, you can use asynchronous operations to update data stored in the state library. Common asynchronous requests include using libraries such as Ajax and axios to send HTTP requests, or using WebSocket for real-time communication .

        Through the cooperation of these concepts, asynchronous requests can be processed in Vuex and the response data can be saved to the state library for use in the application.

  1. Actions : Actions are the place in Vuex used to trigger asynchronous requests and submit mutations. Describe various operations in the application by defining actions, such as obtaining data from the server, updating status asynchronously, etc. You can use asynchronous code in actions and submit mutations through the commit method to update the state when needed.
  2. Mutations : Mutations are where state is modified in Vuex. Asynchronous requests are usually made in actions. When the asynchronous operation is completed, the actions will call the commit method to trigger the corresponding mutation, thereby modifying the state.
  3. Getters : Getters are places in Vuex used to get data from state. You can define some calculated properties in getters and process and filter the status to get the required data.

2. Front-end asynchronous

Write methods in actions.js

export default {
  // context == vue的上下文;payload是vue文件传过来的参数
  setNameAsync: (context, payload) => {

//5秒后调用调方法
    setTimeout(function () {
      context.commit('setName', payload)
    }, 5000)
 }
}

Write events to the page

<template>
  <div>
    <h2>页面一</h2>
    请输入内容:<input v-model="msg"/>
    <button @click="ind">异步改变值</button>

  </div>
</template>
<script>
export default {
  data() {
    return {
      msg: '页面一默认值'
    }
  },
  methods: {
    ind() {
      // setNameAsync setNameAjax
      this.$store.dispatch('setNameAsync', {
        stateName: this.msg,
        _this:this
      })
    }
  }
}
</script>


<style scoped>

</style>

3. ajax request

page

<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 => {

    });
  }
}

backend methods

 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);
    }

Guess you like

Origin blog.csdn.net/weixin_74383330/article/details/133743000