Vue----vuex summary and detailed explanation

This article will cover:

  • What is Vuex?

  • State management model

  • When should you use Vuex?

  • Specific usage

  • Core concepts of each state

     1. state
     2. mutaions
     3. actions
     4. getters
    
  • modular coding

1. What is Vuex?

Vuex is a state management pattern + library developed specifically for Vue.js applications . It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way.

As for the communication method between components, vuex is also a method that can communicate with any component.

2. What is "state management model"?

1. Case introduction

Let's start with a simple Vue counting application:

const Counter = {
    
    
  // 状态
  data () {
    
    
    return {
    
    
      count: 0
    }
  },
  // 视图
  template: `
    <div>{
     
     { count }}</div>
  `,
  // 操作
  methods: {
    
    
    increment () {
    
    
      this.count++
    }
  }
}
 
createApp(Counter).mount('#app')

This state self-management application consists of the following parts:

  • State , the data source that drives the application;
  • Views , which declaratively map state to views;
  • Actions that respond to state changes caused by user input on a view .

Here is a simple illustration representing the idea of ​​"one-way data flow":

Insert image description here

However, the simplicity of one-way data flow is easily broken when our application encounters multiple components sharing state:

  • Multiple views depend on the same state.
  • Actions from different views require changing the same state.

Regarding question 1, the method of passing parameters will be very cumbersome for multi-layer nested components, and it is powerless for state transfer between sibling components.
For question two, we often use parent-child components to directly reference or use events to change and synchronize multiple copies of the state.

These patterns are very fragile and often lead to unmaintainable code.
Therefore, why don't we extract the shared state of the component and manage it in a global singleton mode? In this mode, our component tree forms a huge "view", and any component can obtain status or trigger behavior no matter where it is in the tree!

By defining and isolating the various concepts in state management and maintaining the independence between views and state by enforcing rules, our code will become more structured and maintainable.

Insert image description here

3. Under what circumstances should I use Vuex?

Vuex can help us manage shared state and comes with more concepts and frameworks. This requires weighing short- and long-term benefits.
If you don't plan to develop a large single-page application, using Vuex may be cumbersome and redundant. It's true - if your application is simple enough, you're better off not using Vuex. A simple store pattern is all you need. However, if you need to build a medium to large single-page application, you will most likely be thinking about how to better manage state outside of the component, and Vuex will be a natural choice.

4. Specific usage methods

4.1 Installation

Note: @3 is the version number, vue2 uses vuex@3 version, vue3 uses version 4


// 注释:@3是版本号,vue2用vuex@3版本,vue3用4版本
npm i  -g vue@3  

4.2 Creation of store folder

If you use scaffolding to create it, no operation is required and you can ignore this step.

Concept: The core of every Vuex application is the Store (warehouse). We can say that the Store is a container. The state in the Store is different from a simple global variable, and the state in the Store cannot be directly changed. If you want to change the state, you need to modify it through mutation.

Create the folder store in the src root directory and place index.js under it. It needs to include actions, mutations, and the state structure is as follows:

// 引入vue
import Vue  from 'vue'
 
// 引入vuex
import Vuex from 'vuex'
 
// 应用vue插件
Vue.use(Vuex)
 
// actions响应组件中的动作
const actions = {
    
    
}
 
// mutations操作数据state
const mutations = {
    
    
}
 
// 准备state存储数据
 //数据,相当于data
const state = {
    
    
   //状态对象
}
 
// 创建store并导出
const store = new Vuex.Store({
    
    
        actions,
        mutations,
        state,
})
 
 
//默认导出store
export default store

4.3 Introducing store

Introduce store in main.js, and all global components can use vuex.

import store from './store'

new Vue({
    
    

  render: h => h(App),

  store,

}).$mount('#app')

5. Core concepts of each status

5.1 state

Provides the only public data source. All shared data is stored in the store's state. Similar to data, state is state data. You can directly obtain the state through this.$store.state, or you can use the mapState auxiliary function
provided by vuex. Map state to computed properties.

import Vue from 'vue'
import Vuex from 'vuex'
 
Vue.use(Vuex)
 
export default new Vuex.Store({
    
    
  //数据,相当于data
  state: {
    
     
    sum:0
  },
})

Usage

1. Interpolation reference: { {$store.state.sum}}

2. Use the calculated property
this.$store.state.global data name

  computed:{
    
    
        // 使用计算属性表达
        title( ){
    
    
            return this.$store.state.title;
        },
        singer( ){
    
    
            return this.$store.state.singer;
        }
        
    },

3. Use mapState helper function

Note: The prerequisite for using auxiliary functions is to introduce them first

// 引入mapState,mapGetters
import {
    
    mapState,mapMutations,mapActions,mapGetters} from 'vuex';
computed:{
    
    
    
        // 利用mapState辅助函数的简写形式,代替以上的语句,但本质也是生成计算属性
        ...mapState(['title','singer']),
       
    },

5.2 mutations

The only way to change the modification state in the Vuex 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.

// 操作state中的数据
mutations :{
    
    
    editTitle(state,value){
    
    
        state.title = value;
    },
    editSinger(state,value){
    
    
        state.singer = value;
    }
},

Usage

1. Use commit to trigger the Mutation operation to modify the data in the state

   <button @click="editTitle('Lover')">更改歌名</button>
 
   更改歌手名字
    editTitle(str){
    
    
        this.$store.commit('editTitle',str);
    },

2. Use the mapMutations helper function

 // 利用mapMutation辅助函数的简写形式
    ...mapMutations('options',['editTitle','editSinger']),

5.3 actions

Action submits a mutation rather than directly changing the state. Action can contain any asynchronous operation.
Reason : To facilitate devtools to take a snapshot and save it for management and maintenance. So this is just a specification, not a logical disallowance. It is just to allow this tool to track data changes.
The actions in the corresponding component can be sent through dispatch, and actions can be sent through commit to inform mutations.

   // 相应组件中的动作,组件中可以通过通过dispatch发送,
// actions 通过commit发送动作告知mutations
 actions:{
    
    
    changeSing(context,value){
    
    
        setTimeout(()=>{
    
    
            context.commit('editTitle',value);
                },3000)
    },
    changeSinger(context,value){
    
    
        setTimeout(()=>{
    
    
            context.commit('editSinger',value);
                },3000)
    }
},

Usage

1. Use it in a component and directly use dispatch to trigger the Action function.

 <button @click="changeSing('EndGame')">三秒后更改歌名</button>
 
三秒后更改歌名
    changeSing(str){
    
    
        setTimeout(()=>{
    
    
            this.$store.dispatch('changeSing',str);
        },3000)
    },
     changeSinger(str){
    
    
        setTimeout(()=>{
    
    
            this.$store.dispatch('changeSinger',str);
        },3000)
    }

2. Use mapActions helper function

 // 使用mapActions辅助函数简写形式
    ...mapActions(['changeSing','changeSinger'])

5.4 getters

Similar to computed in Vue, caching is performed to process the data in the Store to form new data.
Sometimes we need to derive some states from the state in the store, such as filtering and counting the list, that is, the state is in Processing:

// 依赖并加工state中的数据,state中的数据也会相应改变
 getters :{
    
    
   otherSong(state){
    
    
        return state.title = 'Delicate'
    }
}

Usage

1. Call data in the component: { {$store.getters.bigNum}}

 otherSong( ){
    
    
            return this.$store.getters.changeOne;
        }

2. Use mapGetters helper function

 // 利用mapGetters辅助函数的简写形似
        ...mapGetters('options',['otherSong'])

6. Modular coding (modules)

Vuex allows us to split the store into modules . Each module has its own state, mutation, action, getter, and even nested submodules - split in the same way from top to bottom and use it in the module: namespaced: true, namespace , after adding, under the current module The identifier can be the same as other modules to resolve naming conflicts between different modules.

6.1 Sample code

import Vue from 'vue';
 
import Vuex from 'vuex';
 
Vue.use(Vuex);
 
const options ={
    
    
    namespaced: true,
 
    // 相应组件中的动作,组件中可以通过通过dispatch发送,
// actions 通过commit发送动作告知mutations
 actions:{
    
    
    changeSing(context,value){
    
    
        setTimeout(()=>{
    
    
            context.commit('editTitle',value);
                },3000)
    },
    changeSinger(context,value){
    
    
        setTimeout(()=>{
    
    
            context.commit('editSinger',value);
                },3000)
    }
},
// 操作state中的数据
mutations :{
    
    
    editTitle(state,value){
    
    
        state.title = value;
    },
    editSinger(state,value){
    
    
        state.singer = value;
    }
},
// 管理store中的数据
state :{
    
    
    title:'Daylight',
    singer:'TaylorSwift'
},
// 依赖并加工state中的数据,state中的数据也会相应改变
 getters :{
    
    
   otherSong(state){
    
    
        return state.title = 'Delicate'
    }
}
 
}
const store = new Vuex.Store({
    
    
   modules:{
    
    
   options
   }
})
export default store;

The above is what I want to share today.

Guess you like

Origin blog.csdn.net/Quentin0823/article/details/135214208