安装
pnpm add pinia
配置
main.ts中创建pinia
import { createPinia } from 'pinia'
const store = createPinia()
app.use(store)
创建store
在src目录下创建store/index.ts
在index.ts中定义容器和数据
import { defineStore } from 'pinia'
export const mainStore = defineStore('mainStore', {
state: () => ({
count: 0,
hello: 'hello',
mobile: '13066668888'
}),
getters: {
handleMobile(state) {
return state.mobile
.toString()
.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
}
},
actions: {
changeState() {
this.count++
this.hello = this.hello + 'bb'
}
}
})
组件中调用状态
<template>
<p>count: {{ count }}</p>
<p>mobile: {{ handleMobile }}</p>
<p>hello: {{ hello }}</p>
<hr />
<p></p>
</template>
<script lang="ts" setup>
import { mainStore } from "@/store";
import { storeToRefs } from "pinia";
const { count, handleMobile, hello } = storeToRefs(mainStore())
</script>
<style scoped>
</style>
组件中处理状态的四种方法
<template>
<div>
<button @click="handleClick">handle with state</button>
</div>
<div>
<button @click="handleClickOne">handle with $patch(obj)</button>
</div>
<div>
<button @click="handleClickTwo">handle with $patch(fn)</button>
</div>
<div>
<button @click="handleClickThree">handle with actions</button>
</div>
</template>
<script lang="ts" setup>
import { mainStore } from "@/store"
const store = mainStore()
// 方法一 直接操作state
const handleClick = () => {
store.count++
}
// 方法二 操作$patch方法,里面传递一个对象
const handleClickOne = () => {
store.$patch({
count: store.count + 1,
hello: store.hello + 'aa'
})
}
// 方法三 操作$patch方法 里面传递一个函数
const handleClickTwo = () => {
store.$patch((state) => {
state.count++
state.hello = state.hello + '1'
})
}
// 方法四 使用actions
const handleClickThree = () => {
store.changeState()
}
</script>
<style scoped>
div {
margin-bottom: 10px;
}
</style>