Vuex使用简介

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

找开项目:Vue.Demo

新建:store.js

import Vue from 'vue'
import Vuex from 'vuex'
import { vuexOidcCreateStoreModule } from 'vuex-oidc'
import { oidcSettings } from './config/oidc'
import { moduleA } from './myStore';

// NOTE: If you want to customize how tokens are stored you can use WebStorageStateStore from oidc-client (see bellow)
// Default storage is window.localStorage
// import { WebStorageStateStore } from 'oidc-client'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        increment(state) {
            state.count++
        }
    },
    actions: {
        /*
        increment(context) {
            context.commit("increment");
        }*/
        increment({ commit }) {
            commit("increment");
        }
    },
    getters: {
        done: state => {
            return state.count;
        }
    },
    modules: {
        myStore: moduleA,
        oidcStore: vuexOidcCreateStoreModule(
            oidcSettings,
            // NOTE: If you do not want to use localStorage for tokens, in stead of just passing oidcSettings, you can
            // spread your oidcSettings and define a userStore of your choice
            // {
            //   ...oidcSettings,
            //   userStore: new WebStorageStateStore({ store: window.sessionStorage })
            // },
            // Optional OIDC store settings
            {
                namespaced: true,
                dispatchEventsOnWindow: true
            },
            // Optional OIDC event listeners
            {
                userLoaded: (user) => console.log('OIDC user is loaded:', user),
                userUnloaded: () => console.log('OIDC user is unloaded'),
                accessTokenExpiring: () => console.log('Access token will expire'),
                accessTokenExpired: () => console.log('Access token did expire'),
                silentRenewError: () => console.log('OIDC user is unloaded'),
                userSignedOut: () => console.log('OIDC user is signed out'),
                oidcError: (payload) => console.log('OIDC error', payload)
            }
        )
    }
})

新建:myStore.js

export const moduleA = {
    namespaced: true,
    mutations: {
        changeName() {
            alert("hi!");
        }
    }
}

我们在组件Welcome.vue中使用一下:

<template>
    <div>
    <router-link :to="{name: 'home'}">to home</router-link>
    <div>
        <button v-on:click="add">Store</button>
    State:{{this.$store.state.count}}<br/>
    MapState:{{count}}<br/>
    mapGetters :{{myDone}}<br/>
    mapMutations:<button v-on:click="increment">Change</button><br/>
    mapActions:<button v-on:click="myIncrement">Change</button><br/>
    myStoreMutations:<button v-on:click="changeName">ChangeName</button>
    </div>
    </div>
</template>

<script>
    import {
        mapState,
        mapGetters,
        mapMutations,
        mapActions
    } from 'vuex';

    export default {
        /*computed: mapState({
            myCount: state => state.count
        }),*/
        computed: {
            ...mapState(["count"]),
            ...mapGetters({
                myDone: "done"
            })
        },
        /*computed: {
            ...mapState({
                myCount: state => state.count
            })
        },*/
        methods: {
            ...mapMutations(["increment"]),
            ...mapMutations('myStore', ["changeName"]),
            ...mapActions({
                myIncrement: 'increment'
            }),
            add() {
                this.$store.commit('increment');
            }
        }
    };
</script>

<style scoped>

</style>

运行效果:

发布了128 篇原创文章 · 获赞 18 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/xiaoxionglove/article/details/102158805