返回列表 发布新帖
查看: 34|回复: 0

Pina的基本使用

发表于 6 天前 | 查看全部 |阅读模式

这里或许是互联网从业者的最后一片净土,随客社区期待您的加入!

您需要 登录 才可以下载或查看,没有账号?立即注册

×
本帖最后由 zzz 于 2025-7-10 17:29 编辑

screenshot_2025-07-10_16-54-05.png
screenshot_2025-07-10_16-54-34.png

安装
  1. yarn add pinia 或 npm install pinia
复制代码
注册 Pinia
  1. import { createPinia } from 'pinia'

  2. app.use(createPinia())
复制代码

通过defineStore 创建 Store
  1. import { defineStore } from 'pinia'
  2. export const useUserStore = defineStore("main", {
  3. });
复制代码
state
  1. import { defineStore } from 'pinia'
  2. const useStore = defineStore('mian', {
  3.   // 推荐使用 完整类型推断的箭头函数
  4.   state: () => {
  5.     return {
  6.       // 所有这些属性都将自动推断其类型
  7.       counter: 0,
  8.       name: 'Eduardo',
  9.       isAdmin: true,
  10.     }
  11.   },
  12. })
复制代码
action
  1. export const useStore = defineStore('main', {
  2.   state: () => ({
  3.     counter: 0,
  4.   }),
  5.   actions: {
  6.     increment() {
  7.       this.counter++
  8.     },
  9.     randomizeCounter() {
  10.       this.counter = Math.round(100 * Math.random())
  11.     },
  12.   },
  13. })
复制代码

getters
  1. export const useStore = defineStore('main', {
  2.   state: () => ({
  3.     counter: 0,
  4.   }),
  5.   getters: {
  6.     doubleCount: (state) => state.counter * 2,
  7.   },
  8. })
复制代码

创建具体 Store(组合式 API )
  1. import { defineStore } from 'pinia',
  2. const useCounterStore = defineStore('counterStore', {
  3.   state: () => ({
  4.     counter: 0
  5.   })
  6. })
复制代码

使用 Store
  1. <script setup>
  2. import { useCounterStore } from "@/stores/counter";
  3. // 注意:这里导入的函数,不能被解构,那么会失去响应式。
  4. // 例如不能这样: const { count } = useCounterStore();
  5. const counterStore = useCounterStore();
  6. </script>
复制代码
读取state
  1. const store = useStore()
  2. store.counter++
复制代码
修改 state
  1. store.$patch({
  2.   counter: store.counter + 1,
  3.   name: 'Abalam',
  4. })
复制代码
重置 state
  1. const store = useStore()
  2. store.$reset()
复制代码
替换 state
  1. store.$state = { counter: 666, name: 'Paimon' }
复制代码


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Copyright © 2001-2025 Suike Tech All Rights Reserved. 随客交流社区 (备案号:津ICP备19010126号) |Processed in 0.135315 second(s), 9 queries , Gzip On, MemCached On.
关灯 在本版发帖返回顶部
快速回复 返回顶部 返回列表