Pinia简单使用

安装

shell 复制代码
# 使用 yarn
yarn add pinia
# 或者使用 npm
npm install pinia

使用

  1. 创建一个js文件store/counter.js
javascript 复制代码
import { defineStore } from 'pinia'

// 第一个参数 counter 是应用中 Store 的唯一ID
export const useCounterStore = defineStore('counter', {
    state: ()=>({
        count: 0,
        name: 'demo'
    }),
    getters: {
        doubleCount: (state)=> state.count*2
    },
    actions: {
        increment() {
            this.count++
        }
    }
})
  1. 组件内使用demo.vue
html 复制代码
<template>
  <div>
    <div>count:{{ count }}</div>
    <div>doubleCOunt:{{ doubleCount }}</div>
    <button @click="add">按钮</button>
  </div>
</template>
<script setup>
import { computed } from 'vue'
import { useCounterStore } from '@/store/counter'

const store = useCounterStore()

// 不可以这样直接解构,会破坏响应式
// const { name, doubleCount } = store

// 获取state的值
const count = computed(()=>store.count)

// 获取getters的值
const doubleCount = computed(()=>store.doubleCount)

// 调用actions修改count
const add = () => {
  store.increment()
}
</script>

页面效果

初始效果

点击按钮后

相关推荐
To_OC1 分钟前
LC 560 和为 K 的子数组:前缀和配哈希表,这对组合我是真的服了
javascript·算法·程序员
浮生望38 分钟前
React 受控与非受控组件:从表单状态管理到实时校验的完整实践
前端
叠层归一研究院1 小时前
AGI 系统(八):符号范畴嵌入函子 — SymCat ↪ C_M107 严格化
c语言·开发语言·人工智能·算法·transformer·agi
明朝百晓生1 小时前
Deep RL learning[2026/8]
开发语言·javascript·人工智能
糖墨夕2 小时前
第二章:AI Agent 到底是个啥?—— 用生活场景把概念讲明白
前端
Csvn2 小时前
⚡ content-visibility: auto —— 长页面渲染提速的隐藏神器,白捡的性能优化
前端
用户938515635072 小时前
ESLint 代码规范完全指南——从 AST 原理到 flat config 逐行解析
javascript·后端·代码规范
用户938515635072 小时前
深入理解 Next.js:从 SPA 的 SEO 问题到约定式路由与 SSR 原理
前端·后端·全栈
weixin-a153003083162 小时前
python-装饰器
开发语言·python
snow@li2 小时前
web:前端500知识点/速查手册
前端