本文最后更新于:2025-11-25T14:34:32+08:00
Pinia的 3 大核心
- 状态(state)
- 派生出新状态(getters)
- 操作(actions)
基础使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import {defineStore} from 'pinia'
const useUserStore = defineStore('user',{ state:()=>({ name:'张三', age:18 }), getters:{ getAge(state){ return state.age } }, actions:{ changeAge(){ this.age++ } } })
|
1 2 3 4
| import {useUserStore} from '@/stores/user' const userStore = useUserStore() userStore.age userStore.changeAge()
|
进阶使用(推荐✅)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import {defineStore} from 'pinia' import {reactive,computed} from 'vue'
export const useUserStore = defineStore('user',()=>{ const Person = reactive({ name:'张三', age:18 }) const getAge = computed(()=>{ return Person.age }) const changeAge = ()=>{ Person.age++ } return { Person, getAge, changeAge } })
|
1 2 3 4
| import {useUserStore} from '@/stores/user' const userStore = useUserStore() userStore.Person.age userStore.changeAge()
|
Pinia笔记
https://zouhualu.github.io/20230619/Pinia笔记/