The use of Vuex is detailed and easy to understand

Table of Contents

I. Introduction

2. Introduction to Vuex

3. Use of vuex

3.1 Install Vuex

3.2 Steps to use Vuex:

4. Vuex’s stored value and value (change value)

5. Asynchronous request of vuex

Okay, that’s it for today’s sharing! ! !


1. Foreword

Today we continue the previous Elementexplaining the use of Vuex. Related articles:
http://t.csdnimg.cn/3hnpNicon-default.png?t=N7T8http://t.csdnimg.cn/3hnpN

2. Introduction to Vuex

Vuex is the official state management model for Vue.js. It is designed to better manage the state of the application and can be easily integrated with Vue.js applications.

The core concepts of Vuex include state, mutations, actions and getters.

  • State: where data is stored. It holds the state of the entire application and can be shared among different components. Access state by using this.$store.state in a Vue component.

  • Mutation: is the only way to change state, similar to the methods attribute of a component. It is synchronous and used to modify data in state.

  • Actions: Actions are used to handle asynchronous operations and submit mutations. They can contain any asynchronous operations, such as asynchronous requests, timers, etc. Actions are triggered through the store.dispatch method.

  • Getters: Getters are used to derive some states from State, similar to computed properties. They can be obtained through the store.getters method.

———Use pictures to understand:

Use of 三.vuex

3.1 Install Vuex

If the node.js version is 10, then use npm install vuex -S

If the node.js version is 18 or above, use npm i -S [email protected]

You can view it in the environment variables in the settings:

Enter in the file directory we use:

View results:

3.2 Steps to use Vuex:

  1. Create store: Create the store.js file in the src directory, introduce Vue and Vuex, and create a new Vuex.Store instance.

  2. Define state: Define a state object in the store.js file to store data.

  3. Define mutations: Define mutations objects in the store.js file, including some methods for modifying state.

  4. Define actions: Define the actions object in the store.js file, including some methods for triggering mutations.

  5. Use Vuex in components: In components that need to use state, obtain the data in the state through this.$store.state.

  6. Trigger mutations and actions in components: In components that need to modify state, mutations are triggered through this.$store.commit, and actions are triggered through this.$store.dispatch.

Four.vuex’s stored value (changed value)

First create a store directory under src and create four js files: state (state), mutations (changes), actions (actions) and getters (getters)

Define the default value in state.js:

export default {
  eduName: 'Default value~~'
}

Set the change value in mutations.js:

export default {
  // type (event type): Its value is setEduName
  // payload: The official gave it a fancy name: payload, which is actually a container that holds the parameters to be passed.
  setEduName: (state, payload) => {
    state.eduName = payload.eduName;
  }
}

Get the value in getters.js:

export default {
  getEduName: (state) => {
    return state.eduName;
  }
}

Create an index.js file in the store directory:

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

Then mount it 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'
import Vuex from 'vuex'

//Mockjs will only be introduced in the development environment
process.env.MOCK & amp; & amp; require('@/mock')

// Newly added 1
import ElementUI from 'element-ui'
// Newly added 2, to avoid different packaging styles later, should be placed before import App from './App';
import 'element-ui/lib/theme-chalk/index.css'
import App from './App'
import router from './router'
//Add vuex
import store from './store'

// Newly added 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 */
newVue({
  el: '#app',
  router,
  store,
  data() {
    return {
      // define bus
      Bus: new Vue()
    }
  },
  components: {
    App
  },
  template: '<App/>'
})

Final test:

page1.vue:

<template>
  <div>
    <h1>First interface</h1>
    Please enter: <input v-model="msg" />
    <button @click="fun1">Get value</button>
    <button @click="fun2">Change value</button>
  </div>
</template>

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

<style>
</style>

page2.vue:

<template>
  <div style="padding: 50px;padding-top: 20px;">
    <h1>Page 2</h1>
    {<!-- -->{eduName}}
  </div>
</template>

<script>
  export default {
    data() {
      return {
        mag: 'Ejection off duty'
      }
    },
    computed: {
      eduName() {
        return this.$store.state.eduName;
      }
    }
  }
</script>

<style>
</style>

Results:

5.vuex asynchronous request

Inside page1:

 <!-- Asynchronous requests can do multiple things at the same time -->
     <button @click="fun3">Change value</button>

 fun3(){
        this.$store.dispatch("setEduNameByAsync",{
          eduName:this.msg
        })
      },

Inside action.js:

 export default {
   setEduNameByAsync: function(context, payload) {
     setTimeout(() => {
       //The setEduName (event type) here refers to the setEduName event in mutations.js
       context.commit('setEduName', payload);
     }, 7000);
     //7000 means to execute this event after 7 seconds
   },
   setEduNameByAjax: function(context, payload) {

     let _this=payload._this;
     //Define the backend request address
     let url = _this.axios.urls.VUEX;
     let params = {
       resturantName: payload.eduName
     }
     _this.axios.post(url, params).then(r => {
       console.log(r);
     }).catch(e => {
       console.log(e);
     });
   }
 }

Result:

Okay, that’s it for today’s sharing! ! !

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 137440 people are learning the system