vuex结构:
index.js
import { createStore } from 'vuex'
import getters from "./getters";
import mutations from "./mutations";
import actions from "./actions";
import createPersistedState from 'vuex-persistedstate'
import animals from './module/animals.js'
export default createStore({
state: {
userInfo: {},
count1: 100,
count2: 10,
arr: []
},
getters,
mutations,
actions,
modules: {
animals
},
plugins: [
createPersistedState({
storage: window.sessionStorage,
paths: ["userInfo", "count1"]
})
]
})
actions.js
export default {
changeArr(context, val) {
val.push('actions中的内容')
context.commit('setArr',val)
}
}
getters.js
export default {
getCountPlus(state, getters) {
return state.count1 + state.count2
}
}
mutations.js
export default {
setUserInfo(state, val) {
state.userInfo = val
},
setArr(state, val) {
state.arr = val
}
}
animals.js
const state = {
type: '',
size: ''
}
const mutations = {
setAnimalType(state, val) {
state.type = val
},
setAnimalSize(state, val) {
state.size = val
}
}
const actions = {}
export default {
namespaced: true,
state,
mutations,
actions
}
页面用法
<template>
<div class="container">
<!-- 测试getter -->
<div>
{{ store.getters.getCountPlus }}
</div>
<el-divider />
<!-- 测试commit -->
<div>姓名:{{ store.state.userInfo.name }}</div>
<div>年龄:{{ store.state.userInfo.age }}</div>
<div>性别:{{ store.state.userInfo.sex }}</div>
<div class="btn" @click="changeState">按钮</div>
<el-divider />
<!-- 测试模块化 -->
<div>类型:{{ store.state.animals.type }}</div>
<div>体型:{{ store.state.animals.size }}</div>
<div class="btn" @click="changeAnimalState">改变animal状态按钮</div>
<el-divider />
<!-- 测试dispatch -->
<div>数组:{{ store.state.arr }}</div>
<div class="btn" @click="changeArrState">改变arr状态按钮</div>
</div>
</template>
<script setup>
import { watch, onMounted } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
const changeState = () => {
store.commit('setUserInfo', { name: '张三', age: 18, sex: '男' })
}
const changeAnimalState = () => {
store.commit('animals/setAnimalType', '猫咪')
}
const changeArrState = () => {
store.dispatch('changeArr', ['哈哈'])
}
// createPersistedState中存在哪里,就能在哪里获取
watch(() => localStorage, (newVal, oldVal) => {
if (newVal && newVal?.vuex) {
console.log('newVal', newVal);
console.log(JSON.parse(newVal.vuex))
}
}, { immediate: true, deep: true })
</script>
<style lang="scss" scoped>
.container {
display: flex;
flex-direction: column;
align-items: center;
}
div {
color: #000;
}
.btn {
width: 400px;
height: 60px;
border: 1px solid;
background-color: #ccc;
}
</style>