在vue3中可以使用Vuex也可以使用pinia,下面我们来讲讲如何在vue中使用vuex
首先下载vuex,
安装依赖库
npm intall vuex --save-dev
配置vuex
在main.ts中引用
import store from './vuex/index';
createApp(App).use(router).use(piniaStore).use(store).mount('#app');
vuex的使用
新建vuex文件夹,新建index.ts
import { createStore } from 'vuex';
// vuex持久化插件
// npm i vuex-persistedstate --save
import createPersistedstate from 'vuex-persistedstate';
import user from './modules/user';
export default createStore({
state: {
num: 10,
sum: 10,
str: '这是store数据',
},
// computed
getters: {
total(state) {
return state.num + state.sum;
},
},
// methods
mutations: {
changeNum(state, val) {
state.num = val;
state.sum = val + 100;
},
},
// 异步
actions: {
changebtn() {
alert('changebtn');
},
},
modules: {
user,
},
// 配置前端持久化插件
plugins: [
createPersistedstate({
key: 'user',
// 可持续文件的
paths: ['user'],
}),
],
});
新建modules文件夹,新建user.ts
export default {
state: { userInfo: 'Admin' },
mutations: {
changeAdmin(state, val) {
state.userInfo = val;
},
},
};
使用Vuex数据
<!--
* @Author: wangyf 1758985226@qq.com
* @Date: 2023-07-05 09:38:38
* @LastEditors: wangyf 1758985226@qq.com
* @LastEditTime: 2023-07-05 13:25:18
* @FilePath: \fast-vue3\src\pages\injectProvide\index.vue
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
<div>
<h1>依赖注入</h1>
<hr />
<br />
<h1>Vuex</h1>
<h1>sotrenum: {{ sotrenum }}------{{ sotrenum2 }}</h1>
<div>storegetters:{{ storegetters }}--------{{ storegetters2 }}</div>
<div><button @click="changeStateNum">mutations修改数据</button></div>
<div>modules的值:{{ modulesValue }}</div>
<div><button @click="changeUserStateNum">user修改数据</button></div>
<!-- -->
<!-- <A /><br /> -->
<!-- <hr /> -->
</div>
</template>
<script setup>
import { ref, provide, computed } from 'vue';
import { useStore } from 'vuex';
// import A from './A.vue';
const store = useStore();
// sotrenum 不是响应式的,不能修改
let sotrenum = store.state.num;
// 响应式的
const sotrenum2 = computed(() => {
return store.state.num;
});
// 非响应式
const storegetters = store.getters.total;
// 响应式
const storegetters2 = computed(() => store.getters.total);
const parentNum = ref(100);
provide('fromParent', parentNum);
const changeStateNum = () => {
store.commit('changeNum', 300);
// store.dispatch('changebtn');
};
// modules的值
const modulesValue = computed(() => {
return store.state.user.userInfo;
});
const changeUserStateNum = () => {
console.log(store);
store.commit('changeAdmin', 'oooooo');
};
</script>
<style></style>