Vue Basics Introduction: Vuex Installation and Use

Vue Basics Introduction: Vuex Installation and Use

This tutorial is an introductory tutorial. If there are any errors, please point them out.

1. What is vuex

Vuex is a state management pattern developed specifically for Vue.js applications. It uses centralized storage to manage the status of all components of the application, and uses corresponding rules to ensure that the status changes in a predictable way. For detailed information, please refer to the official website document vuex.vuejs.org/zh/

The following is a brief introduction to vuex

2. Installation and introduction

Install vuex first.

npm install vuex --save

It can be used after being introduced 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 App from './App'
import router from './router'
//vuex uses import Vuex from 'vuex'

Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        //Global variable count: 31231
    }
})

Vue.config.productionTip = false
    /* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    //vuex must be added to the store,
    components: { App },
    template: '<App/>'
})

3. Use of vuex

<template>
<div>
      The boss has {{showData}}
      <HelloWorld2/>
</div>
</template>

<script>
import HelloWorld2 from './HelloWorld2'
import son from './son'

export default {
name: 'HelloWorld',
data () {
  return {
       message2:"",
       cou
    }
},
components:{
  HelloWorld2,
  son
},computed: {
  showData(){
    return this.$store.state.count;
  }
}
}

</script>
<template>
<div>
The second one has {{$store.state.count}}
</div>
</template>

<script>
export default {
name: 'HelloWorld2',
data() {
      return {
      }
    }
}
</script>

4. Process Introduction

As shown in the figure, when vuex is not used, the process is: view->actions->state->view

After using vuex, the process is vuecomponent->(dispatch)actions->(commit)mutations->(mutate)state->(render)->vuecomponent

5. mutation

State changes, the only way to change the state in the Vuex store is to submit a mutation. Mutations in Vuex are very similar to events: each mutation has a string event type (type) and a callback function (handler). This callback function is where we actually make the state change, and it receives state as the first argument.

// 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 App from './App'
import router from './router'
//vuex uses import Vuex from 'vuex'

Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        //Global variable count: 31231
    },
    //Change state method mutations: {
        //state is the state above
        addData(state) {
            //Change state state.count++
        }
    }
})

Vue.config.productionTip = false
    /* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    //vuex must be added to the store,
    components: { App },
    template: '<App/>'
})

Then perform the change

<template>
<div>
      The boss has {{showData}}
      <HelloWorld2/>
      <button type = "button" v-on:click = "changeData"> Modify button</button>
</div>
</template>

<script>
import HelloWorld2 from './HelloWorld2'
import son from './son'

export default {
name: 'HelloWorld',
data () {
  return {
       message2:"",
    }
},
components:{
  HelloWorld2,
  son
},computed: {
  showData(){
    return this.$store.state.count;
  }
},
methods: {
  //Execute changes changeData(event){
      this.$store.commit("addData");
  }
}
}

</script>

6. Getters filtering

You can limit mutations, for example, if the mutation is less than 0, it cannot be reduced.

// 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 App from './App'
import router from './router'
//vuex uses import Vuex from 'vuex'

Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        //Global variable count: 0
    },
    //Change state method mutations: {
        //state is the state above
        addData(state) {
            //Change state state.count++
        }
    },
    //Filter getters: {
        getState(state) {
            if (state.count >= 5) {
                return 5
            } else {
                return state.count
            }
        }
    }
})

Vue.config.productionTip = false
    /* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    //vuex must be added to the store,
    components: { App },
    template: '<App/>'
})

When calling

<template>
<div>
The second one has {{$store.getters.getState}}
</div>
</template>

<script>
export default {
name: 'HelloWorld2',
data() {
      return {
      }
    }
}
</script>

7.Action--Asynchronous Processing

Action is similar to mutation, except that:

Action submits a mutation, rather than directly changing the state. Action can contain arbitrary asynchronous operations. Mutations can only be processed synchronously
main.js. Here is an example:

// 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 App from './App'
import router from './router'
//vuex uses import Vuex from 'vuex'

Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        //Global variable count: 0
    },
    //Change state method mutations: {
        //state is the state above
        addData(state) {
            //Change state state.count++
        }
    },
    //Filter getters: {
        getState(state) {
            if (state.count >= 5) {
                return 5
            } else {
                return state.count
            }
        }
    },
    actions: {
        //The advantage of the action-triggered mutations method is asynchronous processing addData(context) {
            //Simulate asynchronous setTimeout(() => {
                context.commit('addData')
            }, 1000)
        }
    }
})

Vue.config.productionTip = false
    /* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    //vuex must be added to the store,
    components: { App },
    template: '<App/>'
})

action should be called when sending.

<template>
<div>
      The boss has {{showData}}
      <HelloWorld2/>
      <button type = "button" v-on:click = "changeData"> Modify button</button>
</div>
</template>

<script>
import HelloWorld2 from './HelloWorld2'
import son from './son'

export default {
name: 'HelloWorld',
data () {
  return {
       message2:"",
    }
},
components:{
  HelloWorld2,
  son
},computed: {
  showData(){
    return this.$store.getters.getState;
  }
},
methods: {
  //Execute changes changeData(event){
      //Operation mutations method //this.$store.commit("addData");
      //The action should be operated instead of the mutation method triggered by the action this.$store.dispatch("addData");

  }
}
}

</script>

8.Module

By using a single state tree, all application states are centralized into one large object. When your application becomes very complex, the store object may become quite bloated.

To solve the above problems, Vuex allows us to split the store into modules. Each module has its own state, mutation, action, getter, and even nested submodules - split in the same way from top to bottom:

If the route can be split, the file is not put into main.js and is placed in vuex. Create a new store/index.js

//vuex uses import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        //Global variable count: 0
    },
    //Change state method mutations: {
        //state is the state above
        addData(state) {
            //Change state state.count++
        }
    },
    //Filter getters: {
        getState(state) {
            if (state.count >= 5) {
                return 5
            } else {
                return state.count
            }
        }
    },
    actions: {
        //The advantage of the action-triggered mutations method is asynchronous processing addData(context) {
            //Simulate asynchronous setTimeout(() => {
                context.commit('addData')
            }, 1000)
        }
    }
})

Modify 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 App from './App'
import router from './router'
import store from './store'


Vue.config.productionTip = false
    /* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    //vuex must be added to the store,
    components: { App },
    template: '<App/>'
})

We can also take the state in main.js and create a new store/state.js

export default {
    count: 0
}

Then index.js can be changed to

//vuex uses import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'

Vue.use(Vuex)

export default new Vuex.Store({
    state: state,
    //Change state method mutations: {
        //state is the state above
        addData(state) {
            //Change state state.count++
        }
    },
    //Filter getters: {
        getState(state) {
            if (state.count >= 5) {
                return 5
            } else {
                return state.count
            }
        }
    },
    actions: {
        //The advantage of the action-triggered mutations method is asynchronous processing addData(context) {
            //Simulate asynchronous setTimeout(() => {
                context.commit('addData')
            }, 1000)
        }
    }
})

Summarize

This is the end of this article about vuex installation and usage for vue beginners. For more information about vuex installation and usage, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • The most detailed summary of vuex introduction
  • Vuex Quick Start (easy to understand)
  • Vuex Getting Started Tutorial
  • Simple three-step vuex introduction
  • Vuex Getting Started Tutorial
  • Learn the application of vuex in vue in minutes (beginner's tutorial)
  • Simple Introduction to Vuex
  • Vue.js Practical Vuex Getting Started Tutorial
  • Getting Started Tutorial on How to Use Vuex

<<:  Implementation of two basic images for Docker deployment of Go

>>:  Steps to modify the MySQL database data file path under Linux

Recommend

Detailed explanation of the use cases of Vue listeners

The first one is to use jQuery's ajax to send...

4 ways to avoid duplicate insertion of data in Mysql

The most common way is to set a primary key or un...

Detailed explanation of the use of JavaScript functions

Table of contents 1. Declare a function 2. Callin...

Lombok implementation JSR-269

Preface Introduction Lombok is a handy tool, just...

WiFi Development | Introduction to WiFi Wireless Technology

Table of contents Introduction to WiFi Wireless T...

Solution to MySQL error code 1862 your password has expired

The blogger hasn't used MySQL for a month or ...

Zabbix configuration DingTalk alarm function implementation code

need Configuring DingTalk alarms in Zabbix is ​​s...

Do you know how to use the flash wmode attribute in web pages?

When doing web development, you may encounter the...

mysql workbench installation and configuration tutorial under centOS

This article shares the MySQL Workbench installat...

MySQL statement execution order and writing order example analysis

The complete syntax of the select statement is: S...

How to change the password of mysql5.7.20 under linux CentOS 7.4

After MySQL was upgraded to version 5.7, its secu...

js+canvas realizes code rain effect

This article shares the specific code of js+canva...

Installing the ping tool in a container built by Docker

Because the Base images pulled by Docker, such as...

Docker beginners' first exploration of common commands practice records

Before officially using Docker, let's first f...