Vue3学习——pinia

发布于:2024-02-29 ⋅ 阅读:(80) ⋅ 点赞:(0)
官方:Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。

安装

npm i pinia

引入

import { createPinia } from 'pinia'
const pinia = createPinia()
app.use(pinia)

此时浏览器的vuetool中就会有个菠萝🍍的图标

使用

store/count.ts

import { defineStore } from 'pinia'
export const useCountStore = defineStore('count', {
	state(){
		return {
			token: 'xin',
			name: 'kele'
		}
	},
	action:{},
	getter:{}
})

vue页面

import { useCountStore  } from '@/store/count.ts'
const countStore = useCountStore()
// 获取state中的token
console.log(countStore.token)

修改数据

在vuex中不可以直接改state的值,但pinia可以

  • 方式一
// 直接vue文件改
countStore.token = 'xxin'
  • 方式二
// 批量修改
countStore.$patch({
	token: 'xx',
	name: 'kelele'
})

观察工具pinia是批量变更是一次,所以批量变更推荐使用$patch

  • 方式三
// actions写方法里
export const useCountStore = defineStore('count', {
	state(){
		return {
			token: 'xin',
			name: 'kele'
		}
	},
	action:{
		changeToken() {
			this.token = 'xinxin'
		}
	},
	getter:{}
})

storeToRefs

用于解构store里的数据(不会对方法进行包裹,只对数据ref)

import { storeToRefs } from 'pinia'
const { name } = storeToRefs(countStore)

getter使用

import { defineStore } from 'pinia'
export const useCountStore = defineStore('count', {
	state(){
		return {
			token: 'xin',
			name: 'kele'
		}
	},
	action:{},
	getter:{
		// 箭头函数不能用this
		addToken: state => state.token + '~~',
		// 不传参数state会飘红,不知道return的是什么类型;加个string类型就可以了
		upperName():string{
			return {
				this.name.toUpperCase()
			}
		}
	}
})

getter的数据也可解构拿到

$subscribe

相当于watch

// 监听数据的变化
store.$subscribe((args, state) => {
  console.log('args', args)
  console.log('state', state)
})
本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到