Contents of this article
- Briefly introduce vite and build a vite project.
- install vuex
- Vuex basic introduction
- Using Vuex
Plugin introduction
1. Briefly introduce vite and build a vite project
1.1 What is vite?
Vite is a new front-end building tool that can significantly improve the front-end development experience. It mainly consists of two parts:
- A development server that provides rich built-in functionality based on native ES modules, such as blazingly fast Hot Module Updates (HMR).
- A set of build instructions that use Rollup to package your code, and it is preconfigured to output highly optimized static assets for production environments.
Vite is designed to provide out-of-the-box configuration, while its plugin API and JavaScript API bring a high degree of extensibility, with full type support.
Vite will use esbuild to pre-build dependencies. Esbuild is written in Go and pre-builds dependencies 10-100 times faster than bundlers written in JavaScript.
1.2 Initialize vite
npm init vite@latest
1.3 Create the first vite project
Vuex is a state management pattern + library developed specifically for Vue.js applications. It uses a centralized store to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable manner.
2. Install vuex
npm install vuex@next --save
3. Vuex basic introduction
3.1 vuex
The core of every Vuex application is the store. A "store" is basically a container that contains most of the state in your application. Vuex differs from a pure global object in the following two ways:
Vuex's state storage is reactive. When a Vue component reads state from the store, if the state in the store changes, the corresponding component will be efficiently updated accordingly.
You cannot directly change the state in the store. The only way to change the state in the store is to explicitly commit mutations. This allows us to easily track each state change, allowing us to implement some tools to help us better understand our application.
It mainly contains five parts: State, Getters, Mutations, Actions, Module.
3.1.1 State concept
Vuex uses a single state tree - yes, a single object contains all application level state. So far it exists as a "single source of data (SSOT)". This also means that each application will contain only one instance of the store. A single state tree allows us to directly locate any particular piece of state and easily take a snapshot of the entire current application state while debugging.
3.1.2 Splitting modules (module)
Due to the use of a single state tree, all the state of the application will be aggregated into a relatively large object. When the application becomes very complex, the store object has the potential to become quite bloated.
To solve the above problems, Vuex allows us to split the store into modules. Each module has its own state, mutations, actions, getters, and even nested submodules - split in the same way from top to bottom: thus split into two state management modules here. (test and test1 modules).
//store/test.js
export const test = {
namespaced: true,
state: {
name: '叫我詹躲躲',
gender: '男',
profession: '前端开发',
age: 10
}
}
//store/test1.js
export const test1 = {
namespaced: true,
state: {
name: '二月',
sport: '跑步、代码和音乐',
publics:'叫我詹躲躲',
amount:100
},
}
3.1.3 Namespaced
By default, actions and mutations inside modules 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 currently this is not for functional purposes (just to maintain the status quo to avoid incompatible changes). Care must be taken not to define two identical getters in different, unnamespaced modules and cause errors.
If you want your module to be more encapsulated and reusable, you can make it a namespaced module by adding namespaced: true.
3.1.4 Definition of Getters
Sometimes we need to derive some state from the state in the store, such as:
//store/test.js
export const test = {
namespaced: true,
state: {
name: '叫我詹躲躲',
gender: '男',
profession: '前端开发',
age: 10
},
//从state派生的一些状态,可以将该部分抽离出来成函数方便调用
getters: {
getUserInfo: state => {
return state.name + '的职业是' + state.profession
},
getUserSex: state => {
return state.name + '的性别是' + state.gender
}
},
}
//store/test1.js
export const test1 = {
namespaced: true,
state: {
name: '二月',
sport: '跑步、代码和音乐',
publics:'叫我詹躲躲',
amount:100
},
getters: {
getSport: state => {
return state.name + '喜欢的运行是' + state.sport
},
getPublics: state => {
return state.name + '的公众号是' + state.publics
}
},
}
3.1.5.mutations definition
The only way to change the state in Vuex's store is to commit 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 changes, and it accepts state as the first parameter:
//store/test.js
export const test = {
namespaced: true,
state: {
name: '叫我詹躲躲',
gender: '男',
profession: '前端开发',
age: 10
},
//从state派生的一些状态,可以将该部分抽离出来成函数方便调用
getters: {
getUserInfo: state => {
return state.name + '的职业是' + state.profession
},
getUserSex: state => {
return state.name + '的性别是' + state.gender
}
},
mutations: {
testMutation1(state) {
// 变更状态
state.age++;
},
// 第二个参数是载荷
testMutation2(state, payload) {
state.age += payload.content;
}
},
}
//store/test1.js
export const test1 = {
namespaced: true,
state: {
name: '二月',
sport: '跑步、代码和音乐',
publics:'叫我詹躲躲',
amount:100
},
getters: {
getSport: state => {
return state.name + '喜欢的运行是' + state.sport
},
getPublics: state => {
return state.name + '的公众号是' + state.publics
}
},
mutations: {
test1Mutation1(state) {
state.amount++;
},
// 第二个参数是载荷
test1Mutation2(state, payload) {
state.amount += payload.amount;
}
},
}
3.1.6.actions definition
Action is similar to mutation, the difference is:
Actions submit mutations, not state changes directly.
Action can contain arbitrary asynchronous operations.
//store/test.js
export const test = {
namespaced: true,
state: {
name: '叫我詹躲躲',
gender: '男',
profession: '前端开发',
age: 10
},
//从state派生的一些状态,可以将该部分抽离出来成函数方便调用
getters: {
getUserInfo: state => {
return state.name + '的职业是' + state.profession
},
getUserSex: state => {
return state.name + '的性别是' + state.gender
}
},
mutations: {
testMutation1(state) {
// 变更状态
state.age++;
},
// 第二个参数是载荷
testMutation2(state, payload) {
state.age += payload.content;
}
},
actions: {
testAction1(context) {
context.commit('testMutation1');
},
//通过参数解构来简化代码,testAction1简化为testAction2写法
testAction2({ commit }, payload) {
commit({
type: 'testMutation2',
content: payload.content
});
}
}
}
//store/test1.js
export const test1 = {
namespaced: true,
state: {
name: '二月',
sport: '跑步、代码和音乐',
publics:'叫我詹躲躲',
amount:100
},
getters: {
getSport: state => {
return state.name + '喜欢的运行是' + state.sport
},
getPublics: state => {
return state.name + '的公众号是' + state.publics
}
},
mutations: {
test1Mutation1(state) {
state.amount++;
},
// 第二个参数是载荷
test1Mutation2(state, payload) {
state.amount += payload.amount;
}
},
actions: {
test1Action1(context) {
context.commit('test1Mutation1');
},
test1Action2({ commit }, payload) {
commit({
type: 'test1Mutation1',
content: payload.content
});
}
}
}
The store repository has been maintained to use our state in components.
4. Status usage
4.1 Introduction
//store/index.js 内容
import { createStore } from "vuex";
import { test } from "./modules/test";
import { test1 } from "./modules/test1";
export const store = createStore({
// Vuex允许store分割成小的module,每个模块拥有自己的state、mutation、action、getter;
// 访问test的状态:store.state.test
modules: {
test, //store模块1
test1 //store模块2
}
});
main.js uses
//main.js
import { createApp } from 'vue'
import App from './App.vue'
import { store } from './store'
let app = createApp(App)
app.use(store).mount('#app')
4.2 Using state in components
4.2.1 Using state
state in test
//test里面的状态
<h3>1.test模块state的状态</h3>
<h5>{{userName}}</h5>
<h5>{{userInfo}}</h5>
<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
/* ------------test模块状态-----------------*/
//获取test1模块的状态
const userName = computed(() => store.state.test.name)
const userInfo = computed(
() => store.state.test.name + '的职业是:' + store.state.test.profession
)
</script>
The state in test1
//test1里面的状态
<h3>1.test1模块state的状态</h3>
<h5>{{sport}}</h5>
<h5>公众号:{{publics}}</h5>
//获取test2模块的状态
const publics = computed(() => store.state.test1.publics)
const sport = computed(
() => store.state.test1.name + '喜欢的运动:' + store.state.test1.sport
)
4.2.2 Using getters
Status of test module getters
<h3>2.test模块getters的状态</h3>
<h5>{{getUserInfo}}</h5>
<h5>{{getUserSex}}</h5>
//获取getters
const getUserInfo = computed(() => store.getters['test/getUserInfo'])
const getUserSex = computed(() => store.getters['test/getUserSex'])
Status of test1 module getters
<h3>2.test1模块getters的状态</h3>
<h5>{{getSport}}</h5>
<h5>{{getPublics}}</h5>
//获取getters
const getSport = computed(() => store.getters['test1/getSport'])
const getPublics = computed(() => store.getters['test1/getPublics'])
4.2.3 Using mutations
Use mutations to change the state of the test module age
<h3>3.用mutations改变test模块age的状态</h3>
<button @click="testClick">改变test状态(age)</button>
<h5>{{age}}</h5>
//通过mutations改变状态,改变test模块的age
const age = computed(() => store.state.test.age)
const testClick = () => {
store.commit('test/testMutation1')
}
Use mutations to change the state of the test1 module amount
<h3>3.用mutations改变test1模块amount的状态</h3>
<button @click="test1Click">改变test1状态(amount)</button>
<h5>{{amount}}</h5>
//通过mutations改变状态,改变test1模块的amount
const amount = computed(() => store.state.test1.amount)
const test1Click = () => {
store.commit('test1/test1Mutation1')
}
4.2.4 Using actions
Use actions to change the state of the test module age
<h3>4.用actions改变test模块age的状态</h3>
<button @click="changeActions">改变test状态(age)</button>
<h5>{{age}}</h5>
//通过actions改变状态,改变test模块的age
const changeActions = () => {
store.dispatch('test/testAction1')
}
Use actions to change the state of the test1 module amount
<h3>4.用actions改变test1模块amount的状态</h3>
<button @click="changeActions1">改变test状态(amount)</button>
<h5>{{amount}}</h5>
//通过actions改变状态,改变test模块的amount
const changeActions1 = () => {
store.dispatch('test1/test1Action1')
}
Complete demo example
<template>
<div>
<h2>Vuex状态学习</h2>
<div class="wrapper">
<div class="left-box">
<h3>1.test模块state的状态</h3>
<h5>{{userName}}</h5>
<h5>{{userInfo}}</h5>
----------------------------------------------------------
<h3>2.test模块getters的状态</h3>
<h5>{{getUserInfo}}</h5>
<h5>{{getUserSex}}</h5>
----------------------------------------------------------
<h3>3.用mutations改变test模块age的状态</h3>
<button @click="testClick">改变test状态(age)</button>
<h5>{{age}}</h5>
----------------------------------------------------------
<h3>4.用actions改变test模块age的状态</h3>
<button @click="changeActions">改变test状态(age)</button>
<h5>{{age}}</h5>
</div>
<div class="line"></div>
<div class="right-box">
<h3>1.test1模块state的状态</h3>
<h5>{{sport}}</h5>
<h5>公众号:{{publics}}</h5>
----------------------------------------------------------
<h3>2.test1模块getters的状态</h3>
<h5>{{getSport}}</h5>
<h5>{{getPublics}}</h5>
----------------------------------------------------------
<h3>3.用mutations改变test1模块amount的状态</h3>
<button @click="test1Click">改变test1状态(amount)</button>
<h5>{{amount}}</h5>
----------------------------------------------------------
<h3>4.用actions改变test1模块amount的状态</h3>
<button @click="changeActions1">改变test状态(amount)</button>
<h5>{{amount}}</h5>
</div>
</div>
</div>
</template>
<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
/* ------------test模块状态-----------------*/
//获取test1模块的状态
const userName = computed(() => store.state.test.name)
const userInfo = computed(
() => store.state.test.name + '的职业是:' + store.state.test.profession
)
//获取getters
const getUserInfo = computed(() => store.getters['test/getUserInfo'])
const getUserSex = computed(() => store.getters['test/getUserSex'])
//通过mutations改变状态,改变test模块的age
const age = computed(() => store.state.test.age)
const testClick = () => {
store.commit('test/testMutation1')
}
//通过actions改变状态,改变test模块的age
const changeActions = () => {
store.dispatch('test/testAction1')
}
/* -----------test1模块状态------------------*/
//获取test2模块的状态
const publics = computed(() => store.state.test1.publics)
const sport = computed(
() => store.state.test1.name + '喜欢的运动:' + store.state.test1.sport
)
//获取getters
const getSport = computed(() => store.getters['test1/getSport'])
const getPublics = computed(() => store.getters['test1/getPublics'])
//通过mutations改变状态,改变test1模块的amount
const amount = computed(() => store.state.test1.amount)
const test1Click = () => {
store.commit('test1/test1Mutation1')
}
//通过actions改变状态,改变test模块的amount
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>
5. Plugins
The Vuex store accepts the plugins option, which exposes hooks for each mutation. A Vuex plugin is a function that takes store as its only parameter:
const myPlugin = (store) => {
// 当 store 初始化后调用
store.subscribe((mutation, state) => {
// 每次 mutation 之后调用
// mutation 的格式为 { type, payload }
})
}
5.1 Using plugins
const store = createStore({
plugins: [myPlugin]
})
The above is the use of vuex and the explanation of some parameters. I make a little progress every day. Welcome to learn and communicate together. I'm calling me Zhan hide. Articles are updated from time to time to personal blog ( https://zhanhongzhu.top ), Nuggets, Sifu and WeChat public account [call me Zhan hide]. Improve together, grow together.
Reference article
vuex Chinese documentation: https://vuex.vuejs.org/zh/
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。