Vue3 pinia的使用

Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。

开始使用

安装

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

在 main.js 或 main.ts 文件中进行配置

import { createPinia } from "pinia";
···

const pinia = createPinia();
···

···
app.use(pinia);

定义一个store

Store 是使用 defineStore() 定义的,并且它需要一个唯一名称,作为第一个参数传递:

import { defineStore } from 'pinia'

// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
export const useCountStore = defineStore({
	'main',  // 或者id: 'main',
	// store里的初始值
  	state: (): => ({
	    count: 0
	}),
  getters: {
    getCount() {
      return this.count
    }
  },
  // Actions 相当于组件中的 methods。
  actions: {
    setCount(num) {
      this.count= num
    }
  }
})

在组件中使用

import { useCountStore } from '../stores/countStore'

const countStore = useCountStore()
// 之后就可以使用store里的属性和方法了
countStore.count  // 0
countStore.getCount()  // 0
countStore.setCount(1) // count: 1

持久化Pinia 存储

pinia-plugin-persistedstate 是一个高度可定制的包,为这项任务提供自定义存储、序列化器和路径选择选项。

npm : npm i pinia-plugin-persistedstate
yarn : yarn add pinia-plugin-persistedstate

在 main.js 或 main.ts 文件中进行配置

import piniaPluginPersistedstate from "pinia-plugin-persistedstate";


pinia.use(piniaPluginPersistedstate);

通过在您的 store 中将 persist 属性设置为 true,启用Pinia存储持久性:

import { defineStore } from "pinia";

export const uselistingStore = defineStore(`listingStore`, {
  state: () => {
    return {
      data: [],
    };
  },
  persist: true,
  actions: {
  },
  getters: {

  },
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值