基于Vue3的Pinia 快速上手文档

Pinia是Vue.js官方维护的一个状态管理库用于写组合式api

存值(初始化)

一共有两种写法,一种是类似于选项式的写法,另一种是组合式的写法
属性 :
defineStore:pinia的核心,创建一个状态管理器,接收两个参数,第一个参数指定唯一值(ID、标识),第二个值接收一个对象(配置)
state: 要管理或存放的数据
action: 注意事项:在这里边可以使用this,this指向整个这个store,可以直接拿到state定义的变量
getter: 注意事项:这里边也可以直接使用this,也可以函数接收state

第一种(类似于选项式的写法)
//example.ts
import{defineStore} from 'pinia'
export const useExampleStore = defineStore('example',{
	state(){
		return{
			//要存放的数据
			sum : 0
		}
	},
	actions:{
		increment(){
			//此处的this是指向这个整个store的可以拿到state中存放的值
			this.sum ++
		}
	},
	getters:{
		//getter有两种写法
		bigSum(){
			return this.sum*10
		},
		doubleSum:(state):number => state.sum*2
	}
})
第二种写法(组合式api写法)
//example.ts
import {defineStore} from 'pinia'
import {ref} from 'vue' 
export const useExampleStore = defineStore('example',()=>{
	//需要存放的数据,就和普通的Vue3定义变量一样
	let sum = ref(0)
	//方法
	function increment(){
		sum ++
	}
	
})

取值

在需要用到状态管理的文件中引入我们写好的状态管理文件(example.ts),然后再使用.
hooks的用法差不多

//example.vue
<div>{{exampleStore.sum}}</div>

import { useExampleStore } from '@/store/example.ts'
let exampleStore = useExampleStore()

这个地方也可以通过解构赋值的方式引出来,但会失去响应式,可以使用 storeToRefs ,恢复响应式

//example.vue
<div>{{sum}}</div>

import { storeToRefs } from 'pinia';
import { useExampleStore } from '@/store/example.ts'

let exampleStore = useExampleStore()
let { sum } = storeToRefs(exampleStore)

修改值

不同于VueX需要调用在库中写好的方法来进行修改,Pinia的数据,可以在页面中就像普通变量一样进行修改,也会同步到存储库里.
一共有三种写法

第一种写法
//example.vue
<h1>{{sum}}</h1>
<button @click="add">+1</button>

import { useExampleStore } from '@/store/example.ts'
let exampleStore = useExampleStore()

function add (){
	//如果没对sum进行解构
	exampleStore.sum ++ 
	//如果对sum进行了解构
	sum.value++
}
第二种写法($patch)注意第二种函数式写法会接受一个参数,参数内容包含整个store
//example.vue
<h1>{{sum}}</h1>
<button @click="add">+1</button>

import { useExampleStore } from '@/store/example.ts'
let exampleStore = useExampleStore()

function add (){
	//第一种写法
	exampleStore.$patch({
		sum : exampleStore.sum++
	})
	//第二种写法
	exampleStore.$patch((state)=>{
		state.sum++
	})
}
第三种写法 用到了第一步存值(初始化)中的action中定义的方法
//example.vue
<h1>{{sum}}</h1>
<button @click="add">+1</button>

import { useExampleStore } from '@/store/example.ts'
let exampleStore = useExampleStore()

function add (){
	exampleStore.increment()
	
}

监视pinia中的数据的变化($subscribe)

$subscribe收到两个参数
第一个参数:本次修改的信息(没什么用)
在这里插入图片描述

第二个参数:真正的数据
在这里插入图片描述

//example.vue
import { useExampleStore } from '@/store/example.ts'
let exampleStore = useExampleStore()

exampleStore.$subscribe((mutate,state)=>{
	console.log('产生了变化')
})


还有一些注意事项,初始化的时候设置的函数方法名尽量是use???Store,在页面中引入的时候变量名尽量设置成???Store

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值