一、安装 及 挂载
npm install pinia
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
二、创建 pinia 容器:store
import { defineStore } from 'pinia'
export const usemainStore = defineStore('main', {
state: () => {
return {
count: 100,
foo:'张三',
arr:[]
}
},
getters:{
getCount(state){
return state.count + 10
},
getArr(): number{
return this.arr.length
},
getFoo(state){
return this.getCount() + state.foo
}
},
actions:{
changeState(num: number){
this.count += num
this.foo = 'hello'
this.arr.push(4)
}
}
})
三 、 页面获取 以及 修改
<template>
<button @click="handleChangState()">点击</button>
</template>
<script lang='ts' setup>
import { usemainStore } from '@/store/index'
impost { storeToRefs } from 'pnina'
const mainStore = useMainStore()
console.log(mainStore.count)
const { count , foo } = storeToRefs(mainStore)
console.log(count.value)
const handleChangState = ()=>{
mainStore.count++
mainStore.foo = 'hello'
mainStore.$patch({
count:mainStore.count + 1,
foo:'hello',
arr:[...mainStore.arr,4]
})
mainStore.$patch(state=>{
state.count++
state.foo = 'hellow'
state.arr.push(1)
})
mainStore.changeState(10)
}
</script>