发布于 

pinia

在vue3+ts的环境下使用pinia

  1. 安装

    1
    npm install --save pinia
  2. 在mian.ts中

    1
    2
    3
    4
    5
    import {createPinia} from 'pinia'

    const app = createApp(App)
    app.use(createPinia())
    app.mount('#app')
  3. 在src下创建index.ts 和 types.ts(types.ts是我们用来约束对应模块的状态)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//index.ts
import {defineStore} from 'pinia'
import { indexType } from './types'
//main是storeId,保证唯一
export const useIndexStore = defineStore('index',{
state:():indexType=>{
return {
count:0,
}
},
getters:{
doubleCount():number{
return this.count*2
}
},
actions:{
updateCount(val:number){
this.count = val
}
}
})
1
2
3
4
//types.ts
export type indexType = {
count:number
}
  1. 组件内调用

    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>
  2. 将store的数据变成响应式

    1
    2
    3
    4
    //引入响应式
    import {storeToRefs} from 'pinia'
    const indexStore = useIndexStore()
    const {count} = storeToRefs(indexStore)
  3. 将数据重置为store最初的状态

    1
    indexStore.$reset()
  4. 修改多个数据

    1
    indexStore.$pacth()

详细的pinia教程

https://zhuanlan.zhihu.com/p/533233367