This article directory

  1. Brief introduction to VITE, build vITE project.
  2. Install vuex
  3. Basic introduction to Vuex
  4. Using Vuex
  5. Plug-in to introduce

1. Briefly introduce vITE and build vITE project

1.1 What is vite?

Vite is a new front-end build tool that dramatically improves the front-end development experience. It mainly consists of two parts:

  1. A development server that provides rich built-in features based on native ES modules, such as surprisingly fast module hot update (HMR).
  2. A set of build instructions that use Rollup to package your code and that are pre-configured to output highly optimized static resources for production.

Vite is intended to provide out-of-the-box configuration, while its plug-in API and JavaScript API provide a high degree of extensibility and complete type support. Vite will pre-build dependencies using esBuild. Esbuild is written using Go and is 10-100 times faster than a prepacker-built dependency written in JavaScript.

1.2 Initializing vite

npm init vite@latest
Copy the code

1.3 Create the first Vite project

Vuex is a state management mode + library 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 way.

2. Install vuex

npm install vuex@next --save
Copy the code

3. Basic introduction to Vuex

3.1 vuex

At the heart of every Vuex application is the Store. A “store” is basically a container that contains most of the states in your app. Vuex differs from a purely global object in two ways:

Vuex’s state storage is reactive. When the Vue component reads the state from the Store, if the state in the store changes, the corresponding component is updated efficiently accordingly.

You can’t just change the state in the store. The only way to change the state in a store is to commit mutation explicitly. This allows us to easily track each state change, which allows us to implement tools that help us better understand our application.

It mainly includes five parts: State, Getters, Mutations, Actions and Module.

3.1.1 State concept

Vuex uses a single state tree — yes, it contains all the application-level state in a single object. At this point it exists as a “unique data source (SSOT)”. This also means that each app will contain only one Store instance. A single state tree allows us to directly locate any particular state fragment and easily take a snapshot of the entire current application state during debugging.

3.1.2 Segmentation Module (Module)

Because of the use of a single state tree, all the states of an application are grouped into one large object. When the application becomes very complex, the Store object can become quite bloated. To solve these problems, Vuex allows us to split the Store into modules. Each module has its own state, mutation, action, getter, and even nested submodules — split the same way from top to bottom: hence the split into two state management modules. (Test and test1 modules).

//store/test.js
export const test = {
    namespaced: true.state: {
        name: 'Tell me Jayne to hide.'.gender: 'male'.profession: 'Front-end development'.age: 10}}//store/test1.js
export const test1 = {
    namespaced: true.state: {
        name: '二月'.sport: 'Running, Code and Music'.publics:'Tell me Jayne to hide.'.amount:100}},Copy the code

3.1.3 Namespaced

By default, action and mutation within a module are still registered in the global namespace — this allows multiple modules to respond to the same action or mutation. Getters are also registered in the global namespace by default, but for now this is not for functional purposes (just to maintain the status quo to avoid incompatibility changes). Care must be taken not to cause errors by defining two identical getters in different, namespaceless modules. If you want your modules to be more wrapped and reusable, you can make them namespaced by adding namespaced: True.

3.1.4 Getters definition

Sometimes we need to derive some state from the state in store, such as:

//store/test.js
export const test = {
    namespaced: true.state: {
        name: 'Tell me Jayne to hide.'.gender: 'male'.profession: 'Front-end development'.age: 10
    },
    // Some states derived from state, which can be separated out into functions
    getters: {
        getUserInfo: state= > {
            return state.name + The profession of 'is' + state.profession
        },
        getUserSex: state= > {
            return state.name + The sex of 'is'. + state.gender
        }
    },
}

//store/test1.js
export const test1 = {
    namespaced: true.state: {
        name: '二月'.sport: 'Running, Code and Music'.publics:'Tell me Jayne to hide.'.amount:100
    },
    getters: {
        getSport: state= > {
            return state.name + 'Favorite run is' + state.sport
        },
        getPublics: state= > {
            return state.name + The official number of 'is' + state.publics
        }
    },
}
Copy the code

3.1.5. Mutations are defined

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

//store/test.js
export const test = {
    namespaced: true.state: {
        name: 'Tell me Jayne to hide.'.gender: 'male'.profession: 'Front-end development'.age: 10
    },
    // Some states derived from state, which can be separated out into functions
    getters: {
        getUserInfo: state= > {
            return state.name + The profession of 'is' + state.profession
        },
        getUserSex: state= > {
            return state.name + The sex of 'is'. + state.gender
        }
    },
    mutations: {
        testMutation1(state) {
            // Change the state
            state.age++;
        },
        // The second parameter is the payload
        testMutation2(state, payload){ state.age += payload.content; }}},//store/test1.js
export const test1 = {
    namespaced: true.state: {
        name: '二月'.sport: 'Running, Code and Music'.publics:'Tell me Jayne to hide.'.amount:100
    },
    getters: {
        getSport: state= > {
            return state.name + 'Favorite run is' + state.sport
        },
        getPublics: state= > {
            return state.name + The official number of 'is' + state.publics
        }
    },
    mutations: {
        test1Mutation1(state) {
            state.amount++;
        },
        // The second parameter is the payload
        test1Mutation2(state, payload){ state.amount += payload.amount; }}},Copy the code

3.1.6. Actions defined

Actions are similar to mutation, except that they commit mutation rather than directly changing the state. Actions can contain any asynchronous operation.

//store/test.js
export const test = {
    namespaced: true.state: {
        name: 'Tell me Jayne to hide.'.gender: 'male'.profession: 'Front-end development'.age: 10
    },
    // Some states derived from state, which can be separated out into functions
    getters: {
        getUserInfo: state= > {
            return state.name + The profession of 'is' + state.profession
        },
        getUserSex: state= > {
            return state.name + The sex of 'is'. + state.gender
        }
    },
    mutations: {
        testMutation1(state) {
            // Change the state
            state.age++;
        },
        // The second parameter is the payload
        testMutation2(state, payload){ state.age += payload.content; }},actions: {
        testAction1(context) {
            context.commit('testMutation1');
        },
        // Simplify the code by using argument deconstruction. TestAction1 is simply written as testAction2
        testAction2({ commit }, payload) {
            commit({
                type: 'testMutation2'.content: payload.content }); }}}//store/test1.js
export const test1 = {
    namespaced: true.state: {
        name: '二月'.sport: 'Running, Code and Music'.publics:'Tell me Jayne to hide.'.amount:100
    },
    getters: {
        getSport: state= > {
            return state.name + 'Favorite run is' + state.sport
        },
        getPublics: state= > {
            return state.name + The official number of 'is' + state.publics
        }
    },
    mutations: {
        test1Mutation1(state) {
            state.amount++;
        },
        // The second parameter is the payload
        test1Mutation2(state, payload){ state.amount += payload.amount; }},actions: {
        test1Action1(context) {
            context.commit('test1Mutation1');
        },
        test1Action2({ commit }, payload) {
            commit({
                type: 'test1Mutation1'.content: payload.content }); }}}Copy the code

The Store repository has been maintained to use our state in components.

4. State usage

4.1 introduced

/ / store/index. Js content

import { createStore } from "vuex";
import { test } from "./modules/test";
import { test1 } from "./modules/test1";

export const store = createStore({
  // Vuex allows store to be split into small modules, each with its own state, mutation, action, and getter;
  // Access the state of test: store.state.test
  modules: {
    test, / / store module 1
    test1 / / store module 2}});Copy the code

The main use js

//main.js
import { createApp } from 'vue'
import App from './App.vue'
import { store } from './store'
let app = createApp(App)
app.use(store).mount('#app')
Copy the code

4.2 Use status in components

2 the use of state

The state in test

// The status of the test
<h3>1.Test module state </h3><h5>{{userName}}</h5>
<h5>{{userInfo}}</h5>

<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
/* ------------test module status -----------------*/
// Get the status of module test1
const userName = computed(() = > store.state.test.name)
const userInfo = computed(
  () = > store.state.test.name + 's occupation is:' + store.state.test.profession
)
</script>
Copy the code

State in test1

// The state in test1
<h3>1.Test1 module state </h3><h5>{{sport}}</h5>
<h5>Public number: {{publics}}</h5>

// Get the status of the test2 module
const publics = computed(() = > store.state.test1.publics)
const sport = computed(
  () = > store.state.test1.name + 'Favorite Sport:' + store.state.test1.sport
)
Copy the code

4.2.2 using getters

Status of the test module getters

<h3>2.Test module getters </h3><h5>{{getUserInfo}}</h5>
<h5>{{getUserSex}}</h5>

/ / for getters
const getUserInfo = computed(() = > store.getters['test/getUserInfo'])
const getUserSex = computed(() = > store.getters['test/getUserSex'])

Copy the code

Test1 Module getters status

<h3>2.Test1 module getters </h3><h5>{{getSport}}</h5>
<h5>{{getPublics}}</h5>

/ / for getters
const getSport = computed(() = > store.getters['test1/getSport'])
const getPublics = computed(() = > store.getters['test1/getPublics'])
Copy the code

Holdings using mutations

Change the status of the TEST module AGE using mutations

<h3>3.Change the status of test module AGE using mutations </h3><button @click="testClick">Change the test state (age)</button>
<h5>{{age}}</h5>

// Change the status through mutations, and change the age of the test module
const age = computed(() = > store.state.test.age)
const testClick = () = > {
  store.commit('test/testMutation1')}Copy the code

Change the state of amount on test1 module using mutations

<h3>3.Alter test1 module amount status using mutations </h3><button @click="test1Click">Change the state of test1 (amount)</button>
<h5>{{amount}}</h5>

// Change the status via mutations, and change the amount of the test1 module
const amount = computed(() = > store.state.test1.amount)
const test1Click = () = > {
  store.commit('test1/test1Mutation1')}Copy the code

4.2.4 used actions

Change the state of the test module age with actions

<h3>4.Change the state of the test module age with Actions </h3><button @click="changeActions">Change the test state (age)</button>
<h5>{{age}}</h5>

// Change the state through actions to change the age of the test module
const changeActions = () = > {
  store.dispatch('test/testAction1')}Copy the code

Change the state of amount in module test1 with actions

<h3>4.Alter test1 module Amount status with Actions </h3><button @click="changeActions1">Changing the test state (amount)</button>
<h5>{{amount}}</h5>

// Use actions to change the amount of the test module
const changeActions1 = () = > {
  store.dispatch('test1/test1Action1')}Copy the code

Complete Demo example

<template>
  <div>
    <h2>Vuex state learning</h2>
    <div class="wrapper">
      <div class="left-box">
        <h3>1. State of the test module</h3>
        <h5>{{userName}}</h5>
        <h5>{{userInfo}}</h5>
        ----------------------------------------------------------
        <h3>2. Test module getters status</h3>
        <h5>{{getUserInfo}}</h5>
        <h5>{{getUserSex}}</h5>
        ----------------------------------------------------------
        <h3>3. Change the status of the AGE of the test module using mutations</h3>
        <button @click="testClick">Change the test state (age)</button>
        <h5>{{age}}</h5>
        ----------------------------------------------------------
        <h3>4. Use actions to change the status of the test module age</h3>
        <button @click="changeActions">Change the test state (age)</button>
        <h5>{{age}}</h5>
      </div>

      <div class="line"></div>
      <div class="right-box">
        <h3>1. State of module test1</h3>
        <h5>{{sport}}</h5>
        <h5>Public number: {{publics}}</h5>
        ----------------------------------------------------------
        <h3>2. Test1 module getters status</h3>
        <h5>{{getSport}}</h5>
        <h5>{{getPublics}}</h5>
        ----------------------------------------------------------
        <h3>3. Change the state of amount on test1 module using mutations</h3>
        <button @click="test1Click">Change the state of test1 (amount)</button>
        <h5>{{amount}}</h5>
        ----------------------------------------------------------
        <h3>4. Use actions to change the status of amount in module test1</h3>
        <button @click="changeActions1">Changing the test state (amount)</button>
        <h5>{{amount}}</h5>
      </div>
    </div>

  </div>
</template>
<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
/* ------------test module status -----------------*/
// Get the status of module test1
const userName = computed(() = > store.state.test.name)
const userInfo = computed(
  () = > store.state.test.name + 's occupation is:' + store.state.test.profession
)
/ / for getters
const getUserInfo = computed(() = > store.getters['test/getUserInfo'])
const getUserSex = computed(() = > store.getters['test/getUserSex'])

// Change the status through mutations, and change the age of the test module
const age = computed(() = > store.state.test.age)
const testClick = () = > {
  store.commit('test/testMutation1')}// Change the state through actions to change the age of the test module
const changeActions = () = > {
  store.dispatch('test/testAction1')}/* ----------- module status ------------------*/
// Get the status of the test2 module
const publics = computed(() = > store.state.test1.publics)
const sport = computed(
  () = > store.state.test1.name + 'Favorite Sport:' + store.state.test1.sport
)
/ / for getters
const getSport = computed(() = > store.getters['test1/getSport'])
const getPublics = computed(() = > store.getters['test1/getPublics'])

// Change the status via mutations, and change the amount of the test1 module
const amount = computed(() = > store.state.test1.amount)
const test1Click = () = > {
  store.commit('test1/test1Mutation1')}// Use actions to change the amount of the test module
const changeActions1 = () = > {
  store.dispatch('test1/test1Action1')}</script>

<style scoped>
h2 {
  text-align: center;
}
.wrapper {
  width:1200px;
  margin: 0 auto;
}
.left-box..right-box {
  width:calc(50% - 4px);
  display: inline-block;
  text-align: center;
  background: #c4bebf;
  border-radius: 5px;
}
.line {
  height: 100%;
  width: 4px;
  display: inline-block;
}
</style>
Copy the code

5. The plug-in

Vuex’s store accepts the plugins option, which exposes the hook for each mutation. The Vuex plugin is a function that takes store as its only argument:

const myPlugin = (store) = > {
  // called when store is initialized
  store.subscribe((mutation, state) = > {
    // called after each mutation
    The format of // mutation is {type, payload}})}Copy the code

5.1 Using Plug-ins

const store = createStore({
  plugins: [myPlugin]
})
Copy the code

The above is the use of VUEX and the explanation of some parameters. We are making progress every day. Welcome to learn and communicate with us. I was telling jayne to hide. His articles are periodically updated to his personal blog (Zhanhongzhu. Top), Nuggets, Sifu and wechat official account (call me Zhan Hide hide). Progress together, grow together.

Refer to the article

Vuex Chinese document: vuex.vuejs.org/zh/