安装pinia
npm install pinia
yarn add pinia
import { createPinia } from 'pinia'
const pinia = createPinia()
app.use(pinia)
import { defineStore } from 'pinia'
import { Names } from './store-name'
export const useTestStore = defineStore(Names.TEST,{
state:()=>{
return {
current: 1,
name: 'yx'
}
},
getters:{
},
actions:{
}
})
export const enum Names {
TEST = 'TEST'
}
<template>
<div>
pinia:{{test.name}}
</div>
</template>
<script setup lang="ts">
import { useTestStore } from './stores'
const test = useTestStore()
</script>
- 通过事件方法直接修改test里面的属性
<template>
<div>
pinia:{{test.name}}
</div>
<button @click="changeTest"> change</button>
</template>
<script setup lang="ts">
import { useTestStore } from './stores'
const test = useTestStore()
const changeTest = ()=>{
test.name = '我被改变了'
}
</script>
<style lang="scss" scoped>
</style>
- 通过pinia提供的$patch方法,可批量修改属性
const changeTest = ()=>{
test.$patch({
current: 44444,
name:'hello'
})
}
- 还是通过$patch,只不过里面传递的是函数写法
const changeTest = ()=>{
test.$patch((state)=>{
state.name = '你你你'
})
}
- 使用$state 方法,但要修改state里面所有的值才行,不建议使用
const changeTest = ()=>{
test.$state = {
name: 'hao de',
current: 222
}
}
- 通过 actions 里面的方法,进行修改state
actions:{
setCurrent (num:number = 999){
this.current = num
}
}
import { useTestStore } from './stores'
const test = useTestStore()
const changeTest = ()=>{
test.setCurrent(888)
}
- 获取的test值是可以进行结构的,但不具备响应式,因此使用storeRefs方法让其具备响应式
import { useTestStore } from './stores'
import { storeToRefs } from 'pinia'
const test = useTestStore()
const {current,name} = storeToRefs(test)
const changeTest = ()=>{
current.value++
name.value = '我被改变了'
}