pinia
在vue3+ts的环境下使用pinia
安装
1
npm install --save pinia
在mian.ts中
1
2
3
4
5import {createPinia} from 'pinia'
const app = createApp(App)
app.use(createPinia())
app.mount('#app')在src下创建index.ts 和 types.ts(types.ts是我们用来约束对应模块的状态)
1 | //index.ts |
1 | //types.ts |
组件内调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44<template>
<div>
<h2>Count组件</h2>
<h4>count:{{count}}</h4>
<h4>doubleCount:{{doubleCount}}</h4>
<button @click="countChange">更新pinia->count</button>
</div>
</template>
<script lang="ts">
import { defineComponent,computed } from 'vue'
import {useIndexStore} from '../stores'
export default defineComponent({
name:'Count',
setup () {
const indexStore = useIndexStore()
let doubleCount = computed(()=>indexStore.doubleCount)
let count = computed({
get():number{
return indexStore.count
},
set(val:number):void{
indexStore.updateCount(val)
}
})
const countChange = ():void=>{
console.log(Math.random())
count.value = Math.floor(Math.random()*10)
}
return {
count,
doubleCount,
countChange
}
}
})
</script>
<style scoped>
</style>将store的数据变成响应式
1
2
3
4//引入响应式
import {storeToRefs} from 'pinia'
const indexStore = useIndexStore()
const {count} = storeToRefs(indexStore)将数据重置为store最初的状态
1
indexStore.$reset()
修改多个数据
1
indexStore.$pacth()