7-vue3 vuex4.0-的使用

3,337 阅读1分钟

项目地址 gitee.com/fe521/vue3-…

vuex4.0 的使用

vuex4.0 文档 https://github.com/vuejs/vuex/releases

store

import Vuex from 'vuex';

export default Vuex.createStore({
    state: {
        count: 0
    },
    mutations: {
        increment(state) {
            state.count++;
        },
        decrement(state) {
            state.count--;
        }
    },
    actions: {},
    modules: {}
});

使用 About.vue 文件

<template>
    <div class="about">
        <h1>This is an about page</h1>
        <p>{{ count }}</p>
        <p>
            <button @click="handleDecrement()">减少</button> <br />
            <button @click="handleIncrement()">添加</button>
        </p>
    </div>
</template>
<script>
import {computed} from 'vue';
import {useStore} from 'vuex';
export default {
    name: 'about',
    setup() {
        const store = useStore();

        const count = computed(() => {
            return store.state.count;
        });

        function handleIncrement() {
            store.commit('increment');
        }
        function handleDecrement() {
            store.commit('decrement');
        }

        return {
            count,
            handleIncrement,
            handleDecrement
        };
    }
};
</script>