Understand vuex in 10 minutes

What is vuex?

Vuex is a state management mode specially developed for vue.js applications.

  This state can be understood as an attribute in data, which needs to be shared by other components.
  In other words, it is the data we need to share, and use vuex for unified and centralized management.

In vuex, there are five basic objects by default:

  • state: storage state (variable)
  • Getters: Recompiling before data acquisition can be understood as the calculated attribute of state. We use $sotre.getters.fun() in the component
  • Mutations: Modifies the state and is synchronized. Use $store.commit('',params) in the component. This is similar to the custom event in our component.
  • actions: asynchronous operations. Used in the component is $store.dispath('')
  • Modules: sub-modules of store, used to develop large-scale projects and facilitate state management. We won't explain it here, it's the same as above.

1. First create a vue-cli project

Execute the following command to create a new vue project, the template is webpack, and the name is app

vue init webpack app

2. After the creation is complete, we enter the folder and run the project

cd app
npm run dev

Next, we create a vuex folder in the src directory and create a store.js file
in the vuex folder. The
folder directory looks like this
Insert picture description here
3. Currently we have not introduced vuex, we need to download vuex first, and import it

  After ensuring that we are in our project, enter the following command on the command line to install vuex

npm install vuex --save

Insert picture description here
4. After the installation is successful, we can enjoy our vuex in store.js!

  In the store.js file, introduce vuex and use vuex. Note that my variable names are capitalized Vue and Vuex

<script>
	import Vue from 'vue'
	import Vuex from 'vuex'
	
	Vue.use(Vuex)
	
	const state = {
     
     
	    count: 0
	}
	
	export default new Vuex.Store({
     
     
	    state
	})
</script>

Next, introduce store in main.js

<script>
	import Vue from 'vue'
	import App from './App'
	import router from './router'
	import store from './vuex/store' // 引入store
	Vue.config.productionTip = false
	
	/* eslint-disable no-new */
	new Vue({
     
     
	    el: '#app',
	    router,
	    store,
	    components: {
     
      App },
	    template: '<App/>'
	})
</script>

  However, we can use the count attribute we defined in any component.
  Here we use it in helloWorld to remove the unused tags in helloworld.vue.

<template>
  <div class="hello">
    <h3>{
   
   {$store.state.count}}</h3>
  </div>
</template>

  Open the browser where we just ran the project, you can see that it has been used successfully!
  And in the Vue development tool, we can see the variable count we defined.

  Up to this point, it has been a little and a half! Vuex is very simple, right?
  Recall that we only need to download and install vuex, define the state object in the store.js we defined, and expose it.
  Use our store.js in main.js (this is to prevent it from being referenced in various components, because main.js has our new Vue instance!)
  Now we have used the state in vuex, next we How to manipulate this value? That's right! Use mutations and actions

We continue to operate the store.js file

  We define the mutations object in sotre.js, there are two methods in the object, the parameters in the mutations, the first one is state by default, and the next is a custom parameter.

  We define two methods in mutations, increase and decrease, and set a parameter n, the default value is 0, and then use it in Vuex.Store.

<script>
	/**
	 * mutations 里面放置的是我们操作state对象属性的方法
	 */
	const mutations = {
     
     
	    mutationsAddCount(state, n = 0) {
     
     
	        return (state.count += n)
	    },
	    mutationsReduceCount(state, n = 0) {
     
     
	        return (state.count -= n)
	    }
	}
	export default new Vuex.Store({
     
     
	    state,
	    mutations
	})
</script>

  Then we use this method in helloWorld.vue

  Remember how we use mutations in components? It’s very similar to a custom event

<template>
  <div class="hello">
    <h3>{
   
   {$store.state.count}}</h3>
    <div>
      <button @click="handleAddClick(10)">增加</button>
      <button @click="handleReduceClick(10)">减少</button>
    </div>
  </div>
</template>
<script>
  methods: {
     
     
    handleAddClick(n){
     
     
      this.$store.commit('mutationsAddCount',n);
    },
    handleReduceClick(n){
     
     
      this.$store.commit('mutationsReduceCount',n);
    }
  }
</script>

Come to the browser to see how it works!

  We can see that whenever an event is triggered, we can see the mutations method and parameters we triggered in the vue development tool

perfect!


Next is actions, actions are asynchronous operations

  Create actions object and use

  Here I used two different parameters in the two methods, one is context, which is a parameter with the same object properties as the store object. In the second function, I directly use the commit method of this object.

<script>
const actions = {
     
     
    actionsAddCount(context, n = 0) {
     
     
        console.log(context)
        return context.commit('mutationsAddCount', n)
    },
    actionsReduceCount({
     
      commit }, n = 0) {
     
     
        return commit('mutationsReduceCount', n)
    }
}
export default new Vuex.Store({
     
     
    state,
    mutations,
    actions
})
</script>

  In helloWorld.vue,
  in methods, add two methods, use dispath to trigger

 <div>异步操作</div>
  <div>
    <button @click="handleActionsAdd(10)">异步增加</button>
    <button @click="handleActionsReduce(10)">异步减少</button>
  </div>
<script>
    handleActionsAdd(n){
     
     
      this.$store.dispatch('actionsAddCount',n)
    },
    handleActionsReduce(n){
     
     
      this.$store.dispatch('actionsReduceCount',n)
    }
</script>

  Enter the browser to see how it works!

  The last is getters

  We generally use getters to get our state, because it is a calculated attribute of state

<script>
const getters = {
     
     
    getterCount(state, n = 0) {
     
     
        return (state.count += n)
    }
}
export default new Vuex.Store({
     
     
    state,
    mutations,
    actions,
    getters
})
</script>
<h4>{
   
   {count}}</h4>
<script>
const getters = {
     
     
    getterCount(state) {
     
     
        return (state.count += 10)
    }
}
</script>

  Getters are very simple.

  At this point, if you understand everything, vuex you have no pressure.

  But vuex officially gave us a simpler way to use vuex, which is {mapState, mapMutations, mapActions, mapGetters}

  As long as we understand the above basics, these are not a problem, we just write about them.

  It's that simple, here we use the spread operator of es6. If you are unfamiliar students, go and read the book "Introduction to Es6 Standards" by the great god Ruan Yifeng. I have finished reading it and benefited a lot!

<script>
import {
     
     mapState, mapMutations, mapActions, mapGetters} from 'vuex'
export default {
     
     
  name: 'HelloWorld',
  data () {
     
     
    return {
     
     
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
     
     
    ...mapMutations({
     
     
      handleAddClick: 'mutationsAddCount',
      handleReduceClick: 'mutationsReduceCount'
    }),
    ...mapActions({
     
     
      handleActionsAdd: 'actionsAddCount',
      handleActionsReduce: 'actionsReduceCount'
    })
    // handleAddClick(n){
     
     
    //   this.$store.commit('mutationsAddCount',n);
    // },
    // handleReduceClick(n){
     
     
    //   this.$store.commit('mutationsReduceCount',n);
    // },
    // handleActionsAdd(n){
     
     
    //   this.$store.dispatch('actionsAddCount',n)
    // },
    // handleActionsReduce(n){
     
     
    //   this.$store.dispatch('actionsReduceCount',n)
    // }
  },
  computed: {
     
     
    count(){
     
     
      return this.$store.getters.getterCount
    }
  }
}
</script>

  In the same way, getters and state can also use mapState.
  If you are lazy , mapGetters can use arrays instead of objects, or the object shorthand in es6.

Insert picture description here  The front-end learning is not done overnight. Without stepping, there is no way to reach thousands of miles. Only by continuous hard work can you and me gain something. Professional knowledge can still be learned by institutions. The establishment of training institutions has its inevitability. Are you spending the money right?


Recommended reading:
5 minutes to learn vue routing guards
talk about hooks
vue component design principles
Tree Shaking concept
in-depth interpretation of vue modifier sync

Guess you like

Origin blog.csdn.net/weixin_45820444/article/details/108976010