Vuex

1. Vuex is introduced

Vuex is a state management pattern developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application, and rules to ensure that the state changes in a predictable manner. Vuex is also integrated into Vue’s official debugging tools, providing advanced debugging features such as zero-configuration time-travel debugging, and state snapshot import and export.

###1. Why use Vuex?

In order to realize the complex level of data transfer and sharing between components

  • Vuex is a centralized state (data) management tool developed specifically for vue.js applications.
  • The main thing that Vuex does is to transfer data between components.

###2. What are the components of Vue** basic learning?

  • Father to son: Props
  • Son: $emit
  • Data transfer between sibling components: eventBus event center

3. Core content of Vuex

  • State: State is an object in which all Vuex data is stored.
  • Mutations: All the data to be put into state cannot be put in directly, but must be put in through mutations
  • Actions: Something designed to handle asynchronous operations.

2. Basic use of VUEX

  1. Under the bag
yarn add vuex
Copy the code
  1. Imported into the main. Js
improt Vuex from 'vuex';
Copy the code
  1. Global registration
Vue.use(Vuex); // The install() method in vuex is called
Copy the code
  1. Create a Vuex instance object
const Vuex = new Vuex.store({});
Copy the code
  1. Mount the Store object to the vue object
new Vue({
  render: (h) = > h("#app"),
  store,
});
Copy the code

3. state

State is the property that puts all public state. If you have a public state data, you only need to define it in the state object

// Initialize the vuex object
const store = new Vuex.Store({
  state: {
    // Manage data
    count: 0.name: "Zhang".age: 18,}});Copy the code

There are three ways to call data in state:

  1. Method 1: Obtain count from the state attribute
{{$store.state.count}}</p> </template>Copy the code
  1. Mode 2: State Attribute Definition In the calculation attribute, specified data is automatically mounted to the computed
<template> <p>state: {{count}}</p> </template> <script> export default{computed: { count() { return this.$store.state.count, }, }, } </script>Copy the code
  1. Method 3: Use the helper function – mapState
< span style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 13px! Important; white-space: inherit! Important;" {{ age }}</div> </template> <script> //1. Import {mapState} from "vuex"; Export default{computed: {// 2 Uses the extend operator to map the exported state to the computed properties... mapState(["count", "name", "age"]), }, } </script>Copy the code

4. mutations

Mutations is an object, a method of storing the modified state in the object

Definition of mutations

// Initialize the vuex object
const store = new Vuex.Store({
  state: {
    // Manage data
    count: 0.name: "Zhang".age: 18,},mutations: {
    Parameter 1: must be state, do not pass manually
    // Parameter 2: the parameter payload passed in the call
    addCount(state, count){ state.count += count; ,}}});Copy the code

Two ways to call the method in Mutations:

  1. Method 1: Original form -$store
<template> <div> < button@click ="addCount">count +</button> </div> </template> <script> export default {// $store methods: {addCount() {use this.store.com ("addCount", 10); ,}}}; </script>Copy the code
  1. Method two: auxiliary function – mapMutations
< the template > < div > < button @ click = "addCount (100)" > count 100 + < / button > < / div > < / template > < script > import {mapMutations} from "vuex"; Export default {$store methods: {addCount() {$store methods: {addCount()... mapMutations(["addCount"]), }, }, }; </script>Copy the code

5. actions

When to use **actions **?

  • When we need to perform an asynchronous operation (such as sending a request), we should create an action to perform the asynchronous operation
  • Mutations does not support asynchronous operation

Attention in the use of Actions: the data of state cannot be modified directly, but must be modified indirectly through mutations

There are two types of access:

Define the actions

// Initialize the vuex object
const store = new Vuex.Store({
  state: {... },mutations: {... },actions: {
    getAsyncCount(context) {
      // cintext object -> $store
      // Action cannot do direct operations
      Mutations can be obtained through context.state, refines can be submitted through context.com MIT, and other actions can be called through context.diapatch
      setTimeout(() = > {
        context.commit("addCount".123);
      }, 1000); ,}}});Copy the code
  1. Original call – $store
< span style =" box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 13px! Important; word-break: inherit! Important;" Methods: {addAsyncCount() {//actions - $store this.$store.dispatch("getAsyncCount"); ,}}}; </script>Copy the code
  1. Helper function -mapActions
< span style =" box-sizing: border-box; color: RGB (93, 93, 93); line-height: 20px; font-size: 13px! Important; word-break: inherit! Important;" mapActions } from "vuex"; Export default {methods: {addAsyncCount() {// actions mapActions(["getAsyncCount"]), }, }, }; </script>Copy the code

6. getters

When to use getters?

  • When we have data in a state that we often need to use, we can set up a getters for that data
  • Or we can combine multiple pieces of data into a single getters to provide access
  • Or maybe we need to get the data to calculate, we can create a getters to calculate, and get the final result
  • Getters can be used as a form of providing quick access to data or as a way to similarly compute attributes

There are two ways to use it:

Define getters

// Initialize the vuex object
const store = new Vuex.Store({
  state: {...list: [1.2.3.4.5.6.7.8.9.10]},mutations: {... },actions: {... },getters: {// The first argument to getters is state
    // There must be a return value
    filterList:  state= >  state.list.filter(item= > item > 5)}});Copy the code
  1. Original form -$store
<template>
<div>{{ $store.getters.filterList }}</div>
</template>
Copy the code
  1. Helper function – mapGetters
<template> <div> {{ filterList }} </div> </template> <script> import { mapGetters } from "vuex"; export default { computed: { ... mapGetters(['filterList']) } }; </script>Copy the code

7. Module

Why does Vuex need modularity?

  • All the data are put in state, all the methods of modifying data are put in Mutations, and all the asynchronous operations are put in actions, which will lead to the bloated store object of Vuex, and it will be difficult to do subsequent maintenance and add new functions
  • Through modularization, we can split the store of the main module Vuex into several sub-modules, which makes the functional division clearer and easier to find for subsequent maintenance and update

8. Simple application of modularity

application

Define two modules user and Setting

A status token that manages users in user

Setting Specifies the name of the management application

// Initialize the vuex object
const store = new Vuex.Store({
  state: {... },mutations: {... },actions: {... },getters: {// ...
   token: state= > state.user.token,
   name: state= > state.setting.name,
  },
  modules: {
    user: {
      state: {
        token: "12345",}},setting: {
      state: {
        name: "Vuex instance",},},},});Copy the code

Call:

  1. The original method
< the template > < div > < div > user token {{$store. State. The user. The token}} < / div > < div > site name {{$store. State. Setting. The name}} < / div > < / div >  </template>Copy the code
  1. Access the module data through the mapGetters reference
<template> <div> <div> user token {{token}}</div> <div> site name {{name}}</div> </template> <script> import { mapGetters } from "vuex"; Export default {computed: {// access module data using mapGetters references... mapGetters(["token", "name"]), } }; </script>Copy the code

9. Namespaces in modularity

By default, actions, mutations, and getters within a module are registered in the global namespace — this enables multiple modules to respond to the same mutation or action.

// Initialize the vuex object
const store = new Vuex.Store({
  state: {... },mutations: {... },actions: {... },getters: {// ...
   token: state= > state.user.token,
   name: state= > state.setting.name,
  },
  modules: {
    user: {
    // To keep the internal module closed, we can use namespaced
      namespaced: true.state: {
        token: "12345",},mutations: {
       // In this case, state indicates the state of the user
        updateToken(state) {
          state.token = 678910; }},},setting: {
      state: {
        name: "Vuex instance",},},},});Copy the code

Option 1: Call directly – with the attribute name path of the module

<template> <div> <script> export default {methods: {test () {this.$store.dispatch('user/updateToken') // Call the method directly}}}; </script>Copy the code

Option 2: helper function – path with module’s property name

< img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img > < img >  export default { methods: { ... mapMutations(['user/updateToken']), test () { this['user/updateToken']() } } }; </script>Copy the code

Option 3: createNamespacedHelpers create a namespace based helper function

< span style =" box-sizing: border-box; color: RGB (50, 50, 50); line-height: 20px; font-size: 13px! Important; word-break: inherit! Important;" createNamespacedHelpers } from 'vuex' const { mapMutations } = createNamespacedHelpers('user') export default { methods: {// mapMutations calls... mapMutations(["updateToken"]), } }; </script>Copy the code