import { createStore } from "vuex"
import persistedstate from "vuex-persistedstate";
import user from "./modules/user"
export default createStore({
state: {
num: 10,
sum:10,
str:"这是store数据"
},
getters: {
total(state) {
return state.num+state.sum
}
},
mutations: {
changeNum(state,val) {
state.num = val;
}
},
actions: {
changeBtn() {
alert(1)
}
},
modules: {
user
},
// 持久化存储
plugins: [persistedstate({
key: "vuexStr",
paths:['user']
})]
})
./modules/user
export default {
state: {
userInfo: {
name: '',
age: '',
sex:''
}
},
mutations: {
changeInfo(state:any) {
state.userInfo = {
name: '123',
age: "12",
sex:'男'
}
}
}
}
页面使用:
<template>
<p>num:{{ num }}</p>
<p>total:{{ total }}</p>
<button @click="btnCli">修改值</button>
<p>---------------------</p>
<p>---------------------</p>
<p>---------------------</p>
<p>用户名:{{ userInfo.name }}</p>
<p>性别:{{ userInfo.sex }}</p>
<p>年龄:{{ userInfo.age }}</p>
<button @click="updateUser">修改用户信息</button>
</template>
<script setup lang="ts">
import { computed } from "vue";
import { useStore } from "vuex";
let store = useStore();
let num = computed(() => store.state.num);
let total = computed(() => store.getters.total);
// userinfo
let userInfo = computed(() => store.state.user.userInfo);
console.log(store);
const btnCli = () => {
// store.commit("changeNum", 500);
store.dispatch("changeBtn");
};
const updateUser = () => {
store.commit("changeInfo");
};
</script>
<style></style>
效果图一: