Pinia--Vue存储库,在Vue3+ts中全局定义以及简单使用

本文介绍了如何安装和使用Pinia进行状态管理。首先通过yarn或npm安装Pinia,然后在main.js中引入并配置。接着在test.ts文件中使用defineStore定义store,包含state和actions。在组件中,通过useCounterStore获取store并在setup函数中使用counter的count属性和方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Pinia 中文文档

安装:

yarn add pinia
# 或者使用 npm
npm install pinia

在项目的 main.js 文件中引入:

import { createPinia,Pinia } from "pinia";

const pinia = createPinia();

app.use(pinia);

然后你在项目中定义一个 文件夹: counter==>test.ts

import { defineStore } from "pinia";

export const useCounterStore = defineStore('counter', { // counter为这个存储库的名字
    state: () => {
      return { count: 0 }
    },
    // 也可以定义为
    // state: () => ({ count: 0 })
    actions: {
      increment() {
        this.count++
      },
    },
  })

在组件中使用:

import { useCounterStore } from '@/stores/counter'

export default {
  setup() {
    const counter = useCounterStore(); //这里的counter就是我们在test.ts中的存储库的counter名字

    console.log(counter.count) // 打印: 0

    counter.count++
    // 带自动补全 ✨
    counter.$patch({ count: counter.count + 1 })
    // 或使用 action 代替
    counter.increment()
  },
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

开发那点事儿~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值