1.使用
npm i pinia -S
注:
-g:全局
-save/-S:生产环境需要用到的
-save-dev/-D:只用于开发模式
import { createPinia } from 'pinia'
const store = createPinia()
app.use(store)
2.初始化仓库
store-name.ts中:
export const enum Names {
TEST = 'TEST'
}
index.ts中:
import { defineStore } from "pinia"
import { Names } from "./store-name"
export const useTestStore = defineStore(Names.TEST, {
state: () => {
return {
nm: "xiaobai",
age: 18,
}
},
getters: {},
actions: {},
})
<template>
<div>
{{ Test.nm }}--{{ Test.age }}
</div>
</template>
<script setup lang="ts">
import { useTestStore } from "./store"
const Test = useTestStore()
</script>
3.改变state的值
<template>
<div>
{{ Test.nm }}--{{ Test.age }}
<button @click="addAge">++</button>
</div>
</template>
<script setup lang="ts">
import { useTestStore } from "./store"
const Test = useTestStore()
const addAge = () => {
Test.age++
}
</script>
const addAge = () => {
Test.$patch({
nm: 'xiaohei',
age: 10
})
}
const addAge = () => {
Test.$patch((state) => {
state.nm = 'xiaohei'
state.age = 1
})
}
const addAge = () => {
Test.$state = {
nm: 'xiaohong',
age: 1
}
}
index.ts中:
export const useTestStore = defineStore(Names.TEST, {
state: () => {
return {
nm: "xiaobai",
age: 18,
}
},
actions: {
setAge(num: number) {
this.age = num
}
},
})
app中:
const addAge = () => {
Test.setAge(1)
}
4.解构store
解构后的store是没有响应式的
解决方法:storeToRefs
<script setup lang="ts">
import { useTestStore } from "./store"
import { storeToRefs } from 'pinia'
const Test = useTestStore()
const { nm, age } = storeToRefs(Test)
const addAge = () => {
Test.age++
}
</script>
5.actions/getters使用
actions
同步写法
index.ts中:
type User = {
name: string,
age: number
}
const result: User = {
name: '飞机君',
age: 999
}
export const useTestStore = defineStore(Names.TEST, {
state: () => {
return {
user: <User>{}
}
},
actions: {
setUser() {
this.user = result
}
},
})
app中:
<template>
<p>user-- {{ Test.user }}</p>
<button @click="addUser">++</button>
</template>
<script setup lang="ts">
import { useTestStore } from "./store"
const Test = useTestStore()
const addUser = () => {
Test.setUser()
}
</script>
异步写法