Vue 状态管理 Vuex

1、概述

Vuex作为插件,管理和维护整个项目的组件状态。

2、安装vuex

cnpm i --save vuex

3、vuex使用

github地址:https://github.com/MengFangui/Vuex

new Vue({
    el: '#app',
    router: router,
    //使用vuex
    store: store,
    render: h => {
        return h(App)
    }
});

4、配置项

(1)数据:数据保存在state中。store的数据只能读取,不能改变。

(2)改变store中的数据使用mutations。组件内通过this.$store.commit来执行mutations.

(3)getters提取过滤方法

(4)actions:处理异步操作,组件内通过this.$store.dispatch触发。

涉及数据改变的用mutations,涉及业务逻辑的使用actions。

以上整体配置为:

//vuex的配置
//注意Store是大写
const store = new Vuex.Store({
    //数据保存
    state: {
        count: 0,
        list: [1, 5, 8, 10, 30, 50]
    },
    mutations: {
        increase(state, n = 1) {
            state.count += n;
        },
        decrease(state, n = 1) {
            state.count -= n;
        }
    },
    getters: {
        filteredList: state => {
            return state.list.filter(item => item < 10);
        }
    },
    actions:{
        asyncIncrease(context){
            //异步 1s后执行
            return new Promise(resolve=>{
                setTimeout(()=>{
                    context.commit('increase');
                    //Promise 的一种状态Resolved(已完成)
                    resolve();
                },1000)
            })
        }
    }
});

5、组件代码

<template>
    <div>
        <h1>首页</h1>
        {{count}}
        <button @click="handleIncrease">+5</button>
        <button @click="handleDecrease">-5</button>
        
        <!--getters 用法-->
        <div>{{list}}</div>
        <!--actions用法-->
        <button @click="handleAsyncIncrease">action +1</button>
        
        <!--router-link会渲染为一个a标签 实现跳转的方式1-->
        <!--router-link 的tag属性 指定渲染成什么标签-->
        <!--router-link 的replace属性 不会留下history记录,不能使用后退键-->
        <!--router-link 的active-class属性 路由匹配成功时会自动给当前元素设置为一个名为router-link-active的class-->
        <router-link to="/about">跳转到 about</router-link>
    </div>
</template>
<script>
    export default {
        computed:{
            count(){
                return this.$store.state.count;
            },
            list(){
                return this.$store.getters.filteredList;
            }
        },
        methods:{
            handleIncrease(){
                this.$store.commit('increase',5);
            },
            handleDecrease(){
                this.$store.commit('decrease',5);
            },
            handleAsyncIncrease(){
                this.$store.dispatch('asyncIncrease').then(()=>{
                    console.log(this.$store.state.count)
                });
            }
        }
    }
</script>

vuex 维护多个组件之间的公共(共有)状态!

原文地址:https://www.cnblogs.com/mengfangui/p/8108458.html