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>

页面效果

初始效果

点击按钮后

相关推荐
三两肉7 分钟前
Java 中 ArrayList、Vector、LinkedList 的核心区别与应用场景
java·开发语言·list·集合
yuren_xia9 分钟前
Spring Boot中保存前端上传的图片
前端·spring boot·后端
普通网友1 小时前
Web前端常用面试题,九年程序人生 工作总结,Web开发必看
前端·程序人生·职场和发展
Humbunklung2 小时前
Rust 控制流
开发语言·算法·rust
ghost1433 小时前
C#学习第27天:时间和日期的处理
开发语言·学习·c#
jason成都3 小时前
c#压缩与解压缩-SharpCompress
开发语言·c#
站在风口的猪11083 小时前
《前端面试题:CSS对浏览器兼容性》
前端·css·html·css3·html5
JohnYan3 小时前
Bun技术评估 - 04 HTTP Client
javascript·后端·bun
傻啦嘿哟4 小时前
从零开始:用Tkinter打造你的第一个Python桌面应用
开发语言·c#
三十一6144 小时前
6.4 C++作业
开发语言·c++