Vue3.0 Vuex 安装和使用

# Vue3.0 Vuex 安装和使用

# 安装命令

npm install vuex@4.0.0-beta.4

#OR

npm install vuex@next

# 使用

import {
    createStore
} from "vuex";
//不是在生产环境debug为true
const debug = process.env.NODE_ENV !== 'production';
export default createStore({
	strict:debug,//在不是生产环境下都开启严格模式
    state: {
        is: true,
    },
    mutations: {
        hide(state, type) {
            // 可以接收两个参数,第一个数state数据,第二个数组件中调用store.emit('fun',type)
            state.is = false;
        },
        show(state) {
            state.is = true;
        },
    },
    actions: {},
    modules: {},
    getters: {},
});

# 组件中使用

< template >
    <
    h1 > text页 < /h1> <
h1 v - show = "store.state.is" > text页 < /h1> < /
template >

    export default {
        setup() {
            const store = useStore();
            onMounted(() => {
                //调用 mutations 中的方法,可以传两个参数
                store.commit("hide", "我是hide");
            });
            onUnmounted(() => {
                //调用 mutations 中的方法
                store.commit("show");
            });
            return {
                store, // 解构
            };
        },
    }; <
/script>

# vue3.0Vuex actions

  • vue3.0 使用 vuex 总体来说就是不再用 this 调用 dispatch,而是使用 store
import {
    createStore
} from "vuex";

export default createStore({
    state: {
        is: true,
    },
    mutations: {
        hide(state) {
            state.is = false;
        },
        show(state) {
            state.is = true;
        },
    },
    actions: {
        actionshow(store) {
            store.commit("show");
        },
        actionshide(store) {
            store.commit("hide");
        },
    },
    modules: {},
    getters: {},
});

组件中使用

export default {
    setup() {
        const store = useStore();
        const ishide = () => {
            store.dispatch("actionshide");
        };
        const isshow = () => {
            store.dispatch("actionshow");
        };
        return {
            store,
            ishide,
            isshow,
        };
    },
}; <
/script>