首页 > 其他分享 >pinia快速使用

pinia快速使用

时间:2023-12-26 21:27:07浏览次数:21  
标签:vue const defineStore 快速 pinia 使用 import ref

安装

pnpm add pinia

创建一个pinia实例(根store)并将其传递给应用:

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
const app = createApp(App)

app.use(pinia)
app.mount('#app')

定义Store与使用

通过defineStore()定义,它有两个参数:

  • 第一个参数是一个独一无二的名字
  • 第二个参数是可接受的两类值:Setup函数Option对象

Setup函数

该写法与 Vue 组合式 API 的 setup 函数 相似,我们可以传入一个函数,该函数定义了一些响应式属性和方法,并且返回一个带有我们想暴露出去的属性和方法的对象。

import {ref} from 'vue'
import { defineStore } from 'pinia'
export const userCounterStore = defineStore("counter",()=>{
    //state
    const count =  ref(0)
    //actions
    function increment(){
        count.value++
    }
    //getter
    cont doubleCount = computed(()=>count.value*2)
    return{
        count,
        increment,
        doubleCount
    }
})

Option对象

与vue的选项式API类似,可以传入一个带有stateactionsgetters属性的Option对象

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

认为 state 是 store 的数据 (data),getters 是 store 的计算属性 (computed),而 actions 则是方法 (methods)。

使用Store

<script setup>
import { storeToRefs } from 'pinia'
const store = useCounterStore()

//1.使用storeToRefs()解构赋值保持响应性
const { count, doubleCount } = storeToRefs(store)
// 作为 action 的 increment 可以直接解构
const { increment } = store


//2.直接使用store访问
store.count++
</script>

store 是一个用 reactive 包装的对象
直接使用const { count, doubleCount } = store解构出来的属性(stetegetters)是非响应式的,需要使用storeToRefs()

pinia持久化

pinia 的数据是短时的,只要一刷新页面,数据就会恢复成初始状态,为了避免这个问题,可以对其采用持久化保存方法。使用 pinia-plugin-persistedstate插件

安装

# 安装插件
pnpm add pinia-plugin-persistedstate

引入插件

main.js

//引入插件
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

createApp(App).use(pinia).mount('#app')

使用插件

方法1:默认保存

这种写法会将当前模块中的所有数据都进行持久化保存,默认保存在 sessionStorage 中, key 为模块 id,刷新页面不需要手动读取数据,插件会自动读取。

import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useUserStore = defineStore('user',()=>{
    const name = ref("")
},
{
 	persist:true
})

方法2:设置key、指定保存内容

主动设置 key 名,使用paths指定哪些数据保存

import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useUserStore = defineStore('user',()=>{
    const name = ref("")
    const age = ref("")
},
{
 	persist:{
        key:"info"
        storage: localStorage,
        paths: ['name']
 	}
})
//会保存成info:{}的形式

方式3:对不同数据设置不同的本地存储方式

import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useUserStore = defineStore('user',()=>{
    const name = ref("")
    const age = ref("")
},
{
 	persist:[
         { storage: sessionStorage, paths: ['name'] },
      	 { storage: localStorage, paths: ['age'] },
        ],
 	]
})

进阶用法getItem/setItem

import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useUserStore = defineStore('user',()=>{
    const name = ref("")
    const age = ref("")
    },
 {
    persist:{
        key:"xh_user",
        paths:['name'],
        storage:{
            setItem(key,value) {
                // 使用uni-app的本地缓存方法保存
                uni.setStorageSync(key,value)
            },
            getItem(key) {
                return uni.getStorageSync(key)
            }
        }
    }
})

标签:vue,const,defineStore,快速,pinia,使用,import,ref
From: https://www.cnblogs.com/ewar-k/p/17929370.html

相关文章

  • Day40 数组的使用
    数组的使用1.普通的for循环packagecom.baixiaofan.array;publicclassArrayDemo03{publicstaticvoidmain(String[]args){int[]arrays={1,2,3,4,5};//打印全部数组元素for(inti=0;i<arrays.length;i++){Sys......
  • [20231226]vim Align插件使用例子.txt
    [20231226]vimAlign插件使用例子.txt--//有时候看别人的blog如果遇到执行计划如下,我会使用vim的Align插件做一些处理,好久不用有点生疏,做一个记录:--//假设拷贝和粘贴的执行计划如下:---------------------------------------------------------------------------------------......
  • Android BluetoothAdapter 使用(二)
    AndroidBluetoothAdapter使用(二)本篇文章主要讲下蓝牙设备的配对.1:蓝牙设备列表展示下面是蓝牙设备adapter的代码:packagecom.test.bluetooth;importandroid.bluetooth.BluetoothDevice;importandroid.content.Context;importandroid.view.LayoutInflater;impo......
  • API 参考与帮助内容:一站式开发与使用者支援
    API文档API文档是旨在了解API详细信息的综合指南。通常,它们包括端点、请求示例、响应类别和示例以及错误代码等信息。API文档可帮助开发人员了解API端点的具体细节,并了解如何将API成功集成到他们的软件中。文档生成工具API文档生成工具是直接从源代码创建API文档的......
  • python tkinter 使用(七)
    pythontkinter使用(七)本篇文章主要讲下tkinter中的message控件.Message控件可以用于在窗口中显示一段文本消息.以下是个简单的例子:#!/usr/bin/python3#-*-coding:UTF-8-*-"""@Author:zh@Time2023/11/24上午11:38.@Email:@Describe:"""fromtkinte......
  • python tkinter使用(九)
    pythontkinter使用(九)本文主要讲下scrolledText中图片的插入,以及常见的错误.使用Image.open来打开图片使用ImageTk.PhotoImage()方法将图片转换为tkinter中的图片对象使用insert()方法插入图片ImageTk直接引入后,会遇到如下错误:Traceback(mostrecentcalllast):......
  • python tkinter 使用(二)
    pythontkinter使用(二)本篇文章着重讲下tkinter中messagebox的使用。1:提示框defshowinfo(event):messagebox.showinfo("这是个提示框","thisismessagecontent")2:错误提示框defshowerror(event):messagebox.showerror("这是个错误提示框","thisismessa......
  • python tkinter 使用(十)
    pythontkinter使用(十)#!/usr/bin/python3#-*-coding:UTF-8-*-"""@Author:zh@Time2023/11/27下午3:36.@Email:@Describe:"""importtkinterfromtkinterimport*master=Tk()master.title("菜单")master.ge......
  • python tkinter 使用(三)
    pythontkinter使用(三)本篇文章主要讲下tkinter下的filedialog的使用.1:askopenfilename首先使用tkinter中fiedialog来实现一个简单的文件选择器.这里使用askopenfilename()来启动文件选择器,选择成功后打印下所选文件的名称.#!/usr/bin/python3#-*-coding:UTF-8-*-......
  • python tkinter使用(五)
    pythontkinter使用(五)本篇文章讲述tkinter中treeview的使用Treeview是一个多列列表框,可以显示层次数据。#!/usr/bin/python3#-*-coding:UTF-8-*-"""@Author:zh@Time2023/11/23下午8:28.@Email:@Describe:treeview使用"""importtkinterastkfrom......