vue3+ts项目中使用vuex

39 阅读2分钟

前言

本文整理总结了vuex的使用方法,介绍了关于vuex的五个属性的使用方法,下面有关于各个属性的详细解释,文章最后有整体的代码,可复制到项目中,自己进行效果查看。

vuex的五大属性:state getters mutations actions modules

state

state 是vuex的基本数据,用来存储变量

getters

从基本数据派生的数据,相当于state的计算属性,在store的getters中定义,使用store.getters.计算属性名字来调用

mutations

mutations是提交更新数据的⽅法,必须是同步的(如果需要异步使⽤action)。在 mutations定义操作state变量,在页⾯展⽰的⽅法中通过store.commit()调⽤mutations⾥的⽅法,进⾏操作state。

actions

action 相似于 mutation,但是⽤来代替Mutation进行异步操作的函数

modules

module:可以让每⼀个模块拥有⾃⼰的state、mutation、action、getters,使得结构⾮常清晰,⽅便管理。在module模块中,五⼤属性(state,getters,mutations等等)⽤法差不多跟store的五法属性⽤法差不多。区别就是换地⽅存储操作数据。⽅便管理

整体代码:

main.ts

//引入
import store from "./store";
createApp(App).use(store)

store/index.ts

//import Vuex from "vuex";
import { createStore } from "vuex";
interface stuObj {
    id: number;
    name: string;
    age: number;
}
interface State {
    count: number;
    myName: string;
    students: Array<stuObj>;
}
interface moduleState {
    moduleName: string;
}
const moduleA = {
    state: {
        moduleName: "moduleA"
    },
    getters: {
        fullName(state: moduleState) {
            return state.moduleName + ",我是moduleA的计算属性";
        }
    }
};
const moduleB = {
    state: {
        moduleName: "moduleB"
    },
    getters: {
        fullName(state: moduleState) {
            return state.moduleName + ",我是moduleB的计算属性";
        }
    }
};
//初始化
//export default new Vuex.Store({
export default createStore<State>({
    //配置(state|mutations|actions)
    state: {
        //管理数据
        count: 10,
        myName: "lz",
        students: [
            {
                id: 110,
                name: "zhao",
                age: 19
            },
            {
                id: 111,
                name: "qian",
                age: 17
            },
            {
                id: 112,
                name: "sun",
                age: 28
            },
            {
                id: 113,
                name: "li",
                age: 8
            }
        ]
    },
    getters: {
        //计算属性
        getMyName(state: State) {
            //state参数是固定的,是指获取state的值
            return state.myName + "我是计算属性啊";
        },
        more20Stu(state: State) {
            return state.students.filter((s) => s.age > 20);
        },
        moreAgeStu(state: State) {
            return function (age: number) {
                //调用数组的新特性filter,filter()方法创建一个新的数组,新数组中的元素是通过检查数组
                //中符合条件的所有元素
                return state.students.filter((s) => s.age > age);
            };
        }
    },
    mutations: {
        //this.$store.commit('increment')
        increment(state: State) {
            state.count++;
        },
        incrementCount(state: State, count: number) {
            state.count += count;
        },
        decrement(state: State) {
            state.count--;
        },
        updateNameInfo(state: State, value) {
            state.myName = value;
        }
    },
    actions: {
        //actions相似于mutation,但是用来代替mutation进行异步操作的函数
        updateName(context, payload) {
            setTimeout(() => {
                context.commit("updateNameInfo", payload);
            }, 1000);
        },
        promiseUpdateName(context, payload) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    context.commit("updateNameInfo", payload);
                    resolve("成功修改");
                }, 1000);
            });
        }
    },
    modules: {
        a: moduleA,
        b: moduleB
    }
});

views/parent.vue

<template>
    <div>
        
        {{ store.state.count }}
        <h2>-------vue计算属性getters--------</h2>
        <h3>获取计算属性的getMyName的值:{{ store.getters.getMyName }}</h3>
        <h3>通过vuex的getters获取state的学生大于20岁的对象为: {{ store.getters.more20Stu }}</h3>
        <h3>给计算属性传值需要返回一个方法接收:{{ store.getters.moreAgeStu(18) }}</h3>
        <hr />
        <h1>-------mutations--------</h1>
        <h2>store的count值:{{ store.state.count }}</h2>
        <button @click="addtion">+</button>
        <button @click="subtion">-</button>
        <button @click="addCount(5)">+5</button>
        <button @click="addCount(10)">+10</button>
        <hr />
        <h1>-------actions--------</h1>
        <h2>通过action修改name:{{ store.state.myName }}</h2>
        <button @click="updateName">确定修改</button>
        <button @click="promiseUpdateName">promise回调修改</button>

        <br />
        <h1>-------modules--------</h1>
        <h2>modulesA:{{ store.state.a.moduleName }}</h2>
        <h2>modulesB:{{ store.state.b.moduleName }}</h2>
    </div>
</template>
<script lang="ts" setup>
//页面引入
import { useStore } from "vuex";
const store = useStore();
const addtion = () => {
    store.commit("increment");
};
function subtion() {
    store.commit("decrement");
}
function addCount(count: number) {
    store.commit("incrementCount", count);
}
function updateName() {
    store.dispatch("updateName", "我是action");
}
function promiseUpdateName() {
    store.dispatch("promiseUpdateName", "我是携带的信息").then((res: any) => {
        alert("action已经提交修改,并返回的参数:", +res);
    });
}
</script>

展示情况:

image.png