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>

页面效果

初始效果

点击按钮后

相关推荐
问心无愧05134 小时前
ctf show web入门160 161
前端·笔记
xxie1237944 小时前
return与print
开发语言·python
秋94 小时前
从 Python 后端工程师转型 AI Engineer(AI 工程化)的完整补课清单(2026实战版)
开发语言·人工智能·python
李小白664 小时前
第四天-WEB服务器基本原理,IIS服务
运维·服务器·前端
程序员二叉4 小时前
【Java】 异常高频面试题精讲 | 易错点+对比总结
java·开发语言·面试
humcomm4 小时前
AI编程时代新前端职位
前端·ai编程
好家伙VCC5 小时前
Web Components主题热切换方案揭秘
java·前端
慕木沐5 小时前
Google ADK Java 1.0版本 核心机制与实战 Demo
java·开发语言·python
Roann_seo%5 小时前
C++文件操作完全指南:从文本读写到二进制文件处理
开发语言·c++
甲维斯5 小时前
Kimi版超级玛丽效果“惊人”,配额不足5厘米!
前端·人工智能