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>

页面效果

初始效果

点击按钮后

相关推荐
佛系打工仔1 小时前
绘制K线第二章:背景网格绘制
android·前端·架构
LawrenceLan2 小时前
Flutter 零基础入门(十一):空安全(Null Safety)基础
开发语言·flutter·dart
txinyu的博客3 小时前
解析业务层的key冲突问题
开发语言·c++·分布式
明天好,会的3 小时前
分形生成实验(五):人机协同破局--30万token揭示Actix-web状态管理的微妙边界
运维·服务器·前端
码不停蹄Zzz3 小时前
C语言第1章
c语言·开发语言
C_心欲无痕3 小时前
nginx - alias 和 root 的区别详解
运维·前端·nginx
行者963 小时前
Flutter跨平台开发在OpenHarmony上的评分组件实现与优化
开发语言·flutter·harmonyos·鸿蒙
阿蒙Amon4 小时前
C#每日面试题-Array和ArrayList的区别
java·开发语言·c#
SmartRadio4 小时前
ESP32添加修改蓝牙名称和获取蓝牙连接状态的AT命令-完整UART BLE服务功能后的完整`main.c`代码
c语言·开发语言·c++·esp32·ble