一 、Vuex 是什么?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
二、安装
npm install vuex@next --save
三、核心概念
- state
存储共享数据 官方链接 - getter
store 的计算属性 官方链接 - mutation
更改 Vuex 的 store 中的状态的唯一方法 官方链接 - action
用来提交mutation 官方链接 - module
将 store 分割成模块,每个模块拥有自己的 state、mutation、action、getter 官方链接
四、示例
1、简单使用(单个index.js文件)
文件目录
index.js文件
import { createStore } from "vuex";
const store = createStore({
state: () => ({
name: "vuex",
}),
getters: {
getName(state) {
return state.name;
},
},
mutations: {
changeName(state, data) {
state.name = data;
},
},
actions: {
dispatchChangeName(context, data) {
context.commit("changeName", data);
},
},
});
export default store;
main.js文件
import { createApp } from "vue";
import App from "./App.vue";
import store from "./store";
const app = createApp(App);
app.use(store);
app.mount("#app");
helloWorld.vue
<script setup>
import { ref } from "vue";
import { useStore } from "vuex";
defineProps({
msg: String,
});
const count = ref(0);
const store = useStore();
const mutationChangeName = () => {
store.commit("changeName", "我是mutation修改后的名字vuex");
};
const dispatchChangeName = () => {
store.dispatch("dispatchChangeName", "我是dispatch修改后的名字vuex");
};
</script>
<template>
<h1>{{ msg }}</h1>
<p>通过store.state.name获取的名字:{{ store.state.name }}</p>
<p>通过store.getter获取的名字:{{ store.getters.getName }}</p>
<button @click="mutationChangeName">mutation修改名字</button>
<button @click="dispatchChangeName">dispatch修改名字</button>
</template>
2、拆分index.js
index.js有四个部分:state,getters,mutations,actions等,分别拆分为四个文件是 state.js, getters.js,mutations.js,actions.js。
- state.js
// 方法一:返回箭头函数 函数的返回值是一个对象
// export default () => ({
// name: "vuex",
// });
// 方法二: 返回普通函数 函数的返回值是一个对象
export default function () {
return {
name: "vuex",
// ...
};
}
- getters.js
export default {
getName(state) {
return state.name;
},
// ...
};
- mutations.js
export default {
changeName(state, data) {
state.name = data;
},
// ...
};
- actions.js
export default {
dispatchChangeName(context, data) {
context.commit("changeName", data);
},
// ...
};
- index.js拆分后变成
import { createStore } from "vuex";
import state from "./state";
import getters from "./getters";
import mutations from "./mutations";
import actions from "./action";
const store = createStore({
// es5写法
// state: state,
// getters: getters,
// mutations: mutations,
// actions: actions,
// es6写法
state,
getters,
mutations,
actions,
});
export default store;
五、最后
仓库地址:https://gitee.com/shen-zhanyong/vuex-no-modulesv.git
关于modules如何使用请访问gitee仓库 https://gitee.com/shen-zhanyong/vuex-has-modulesv.git