sps-vue-store
v1.0.3
Published
基于 vue3 + ts 的轻量级状态管理
Downloads
2
Readme
sps-vue-store
基于 vue3 + ts 的轻量级状态管理
安装依赖
npm install sps-vue-store -s
or
yarn add sps-vue-store -s
使用示例
创建仓库
import { createStore } from 'sps-vue-store'
const store = createStore()
export default store
注册模块
import { createStoreModule, Getter, Module, StoreModule } from 'sps-vue-store'
import store from '.'
@Module({ name: 'app', store })
class AppStore extends StoreModule {
public token: string = '123'
@Getter
get tokenWithPrefix() {
return `token is ${this.token}`
}
@Mutation
SET_TOKEN(token: string) {
this.token = token
}
@Action
async asyncSetToken(token: string) {
this.SET_TOKEN(
await new Promise((resolve) => {
setTimeout(() => {
resolve(token)
}, 1000)
})
)
}
}
const useAppStore = createStoreModule(AppStore)
export default useAppStore
操作数据
tsx 语法
import { defineComponent } from 'vue'
import useAppStore from '@/store/app'
export default defineComponent({
name: 'App',
setup() {
const { SET_TOKEN, asyncSetToken } = useAppStore
/* render 函数 */
return () => {
const { token, tokenWithPrefix } = useAppStore
return (
<div>
<div>{token}</div>
<div>{tokenWithPrefix}</div>
<div>
<button onClick={() => SET_TOKEN('456')}>同步</button>
</div>
<div>
<button onClick={() => asyncSetToken('789')}>异步</button>
</div>
</div>
)
}
}
})
sfc 语法
<template>
<div>
<div>{{ appStore.token }}</div>
<div>{{ appStore.tokenWithPrefix }}</div>
<div>
<button @click="SET_TOKEN('456')">同步</button>
</div>
<div>
<button @click="asyncSetToken('789')">异步</button>
</div>
</div>
</template>
<script lang="ts">
import { computed, defineComponent } from 'vue'
import useAppStore from '@/store/app'
export default defineComponent({
name: 'App',
setup() {
const { SET_TOKEN, asyncSetToken } = useAppStore
// 属性与getter在computed中解构,保持其动态特性
const appStore = computed(() => {
const { token, tokenWithPrefix } = useAppStore
return {
token,
tokenWithPrefix
}
})
return {
appStore,
SET_TOKEN,
asyncSetToken
}
}
})
</script>