I believe that vuex is familiar to all of you, and it is also very easy to use. But how much do you know about the principle? Let’s take a look at how VUex works.

Vuex is a state management mode developed specifically for vue.js applications to help us manage shared state.

How do I use Vuex in Vue? Here’s a look at the correct posture for Vuex:

  • Introduce the Vuex plug-in
// store.js
Vue.use(Vuex);
Copy the code
  • Instantiate the vuex. Store class and pass in some configuration, using counters as an example;
// store.js const store = new Vuex.Store({ state:{ count:0 }, mutations:{ increment(state){ state.count++; }, del(state){ state.count--; }, }, actions:{ asyncAdd({commit}){ setTimeout(() => { commit("increment"); }, 2000); }}})Copy the code
  • Component
<template> <div> counter <span>{{$store.state.count}}</span> <br/> <button @click="this.add">+</button> <button @click="this.del">-</button> < button@click ="this.asyncAdd"> asyncAdd +</button> </div> </template> <script> export default { methods:{ add(){ this.$store.commit('increment'); }, del(){ this.$store.commit('del'); }, asyncAdd(){ this.$store.dispatch('asyncAdd'); } } } </script>Copy the code

Vuex core source code analysis:

Goal:

  • As a plug-in there must be install method, can be mixed in, when Vue instantiated before mounting the store instance to its configuration, store on the prototype, so as to be globally available;
  • Hold the basic state, save the configurations of mutations and Actions when instantiating the router;
  • Commit and Dispatch methods can be implemented to modify the state

Vuex core source code brief version:

let Vue; Class Store {// Hold state, Mutations = options. Mutations; return (options){this.state = new Vue({data:options. // mutations is the object this.actions = options. Actions; // mutations is an object // this = this.committee.this.mit (this); this.dispatch=this.dispatch.bind(this); Mutations [type](this.state,arg); } dispatch(type,arg){ console.log(this.actions[type]) return this.actions[type](this,arg) } } function install(_vue){ Vue = _vue; Vue. Mixin ({// why mixin? Use is executed first, while this refers to the vue instance created after main.js, BeforeCreate (){if (this.$options.store) {vue.prototype.$store=this.$options.store; } } }) } export default { Store, install }Copy the code

conclusion

In fact, vuex. Store is a class, and when you use it, you pass in parameters (state, mutations, actions) and let it instantiate it. You assign this instance to Vue, and Vuex assigns it to $Store on the Vue prototype for you. Vuex also gives you a commit and dispatch method that allows you to change the state of store. State, which you can also use to change the state of store