vue3 vuex typescript 组合式风格 持久化 vuex-persist
car.ts 文件
import type { Module, ActionTree, MutationTree, GetterTree } from 'vuex'
interface ICar3Root
{
}
interface ICar3 extends ICar3Root
{
Price:number
}
const car3Store:Module<ICar3, ICar3Root> = {
namespaced: true,
state: {
Price: 0
},
getters: {
getPrice (state) {
return state.Price
}
},
actions: {
setPriceAsync ({ commit }, paylaod) {
commit('setPrice', paylaod)
}
},
mutations: {
setPrice (state, paylaod) {
state.Price = paylaod
}
}
}
export default car3Store
index.ts 主文件
import VuexPersistence from 'vuex-persist'
const vuexLocal = new VuexPersistence({
storage: window.localStorage
})
import { createStore } from 'vuex'
import VuexPersistence from 'vuex-persist'
import car3Store from './car3/car3'
import carStore from '@/store/car/car'
import type { ICarStore } from '@/store/car/car'
export interface StateAll {
CarStore: ICarStore
}
const vuexLocal = new VuexPersistence({
storage: window.localStorage
})
export default createStore({
modules: {
car: carStore,
car3: car3Store
},
plugins: [vuexLocal.plugin]
})
调用
<template>
<div>
<h2>数据绑定 价格</h2>
<div>
<label for="">价格</label>{{price}}
</div>
<h2>利用计算属性 store.state.car3方式获取 </h2>
<div>
<label for="">价格</label>{{cprice}}
</div>
<div>
<div>
价格 <el-input v-model="price"></el-input>
</div>
<div>
价格 计算属性 {{ cprice }}
</div>
<div>
{{ computedPrice }}
</div>
<el-button type="info" @click="setPriceClick">点击同步价格</el-button>
<el-button type="danger" @click="setPriceAsyncClick">点击异步价格</el-button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue'
import { useStore } from 'vuex'
const price = ref(0)
const store = useStore()
// 计算属性 获取 state
const cprice = computed(() => store.state.car3.Price)
const setPriceClick = () => {
store.commit('car3/setPrice', price.value)
}
const setPriceAsyncClick = () => {
store.dispatch('car3/setPriceAsync', price.value)
}
// 计算属性 获取store 中的 getters
const computedPrice = computed(() => store.getters['car3/getPrice'])
</script>
<style lang="scss" scoped>
</style>
浙公网安备 33010602011771号