Introduction and use of Vuex

Vuex is a state management mode developed specifically for Vue.js applications.

  1. Vuex solves the problem of sharing the unified state between components (solves the data sharing between non-parent-child and sibling components)
  2. Data persistence in components

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 manner. Vuex is also integrated into Vue's official debugging tool
devtools, extension, and provides many advanced debugging functions such as zero-configuration time-travel debugging, state snapshot import and export, etc.

Vuex is not recommended for small projects

Vuex core concepts

1、State
2、Getter
3、Mutation
4、Action
5、Module

Use of Vuex

1. Install vuex
npm install vuex --save
2. Create a new vuex folder under src 3. Create a new store.js in the
vuex folder Import and use vuex

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const state = new Vuex.Store({
    
    
    /** 1、state 在 vuex 中用于存储数据 */
    state: {
    
    
        count: 1
    },
    /** 2、mutations 里面放的是方法,主要用于改变 state 里面的数据 */
    mutations: {
    
    
        incCount(state, data){
    
    
            // state 是上面的数据,data是传过来的值
            ++state.count;
        }
    },
    /** 3、类似计算属性,改变 state 里面的 count 数据的时候会触发
        getters里面的方法 获取新的值 */
    getters: {
    
    
        computed: (state) =>{
    
    
            console.log(state.count);
        }
    },
    /** 4、Action 类似于 mutations,不同在于:
            Action 提交的是 mutation,而不是直接变更状态。
            Action 可以包含任意异步操作。 */
    action: {
    
    
        ioncMutationsCount(context){
    
    
            ... /* 异步操作 */
            
            /** 执行 mutations 里面的 incCount 方法 */
            context.commit('incCount');
            
            ... /* 异步操作 */
        }
    },
})

export default store;

4. Introduce stroe.js to the page that needs to share data

<template>
    <div>
        {
    
    {
    
    this.$store.state.count}}
        <br>
        <button @click="incCount()">增加数量+</button>
    </div>
</template>
<script>
import store from '../vuex/store.js';

exprot default{
    
    
    data(){
    
    
        return{
    
    
            msg: '我是一个home组件'
        }
    },
    store,
    methods:{
    
    
        incCount(){
    
    
            // 改变 vuex store 里面的数据, 触发 state 里面的数据
            this.$store.commit('incCount', 123456);
            // 123456 是传递过去的数值,在方法中定义了 data 来接收
            // 触发 actions 里面的方法
            this.$store.dispath('incMutationsCount');
        }
    }
}
</script>

Guess you like

Origin blog.csdn.net/qq_25992675/article/details/105871382