pinia 的 基本使用

一、安装 及 挂载

	// 安装
	npm install pinia
	// 引入
	import { createPinia } from 'pinia'
	// 创建 pinia 实例
	const pinia = createPinia()
	// 挂载到 Vue 根实例
	const app = createApp(App)
	app.use(pinia)
	app.mount('#app')
	

二、创建 pinia 容器:store

  	//  src 下新建文件 store/index.ts
  	// 1. 定义容器 并导出容器
  	// 2. 使用容器的 state
  	// 3. 修改 state
  	// 4. 容器的 action 的使用
  	
	import { defineStore } from 'pinia'

  	// 参数1:容器ID,必须唯一,将来 Pinia 会把所有的容器挂载到跟容器
  	// 参数2:选项对象
  	export const usemainStore = defineStore('main', {
  		// 类似组件的 data , state 存储全局状态
  		// 1.必须是函数:这样是为了在服务器端渲染的时候避免交叉请求导致的数据污染
  		// 2.必须是箭头函数:为了更好的 TS 类型推导
		state: () => {
			return {
				count: 100,
				foo:'张三',
				arr:[]
			}	
		},
		
		// 类似于组件的 computed , 用来封装计算属性, 有缓存的功能
		getters:{
			// 函数接受一个可选参数: state
			getCount(state){
				return state.count + 10
			}// 如果 getters 中没有传state, 则必须手动指定返回值的类型, 否则类型推导不出来
			getArr(): number{
				return  this.arr.length
			},
			// 可调用其他 getters 方法  或者 其他容器
			getFoo(state){
				return  this.getCount() + state.foo
			}
			
		},
		
		// 类似组件的 methods , 封装业务逻辑 , 修改 state
		actions:{
			// 不要使用 箭头函数定义 action, 因为箭头有函数绑定外部 this
			changeState(num: number){
				this.count += num
				this.foo = 'hello'
				this.arr.push(4)
				  // 或
				  // this.$patch({})
				  // this.$patch(state =>{})
			}	
		}
	})
  

三 、 页面获取 以及 修改

	<template>
		<button @click="handleChangState()">点击</button>
	</template>
  	<script lang='ts' setup>
  	import { usemainStore } from '@/store/index'
  	impost { storeToRefs } from 'pnina'
  	const mainStore = useMainStore()
	
	// 使用方法1:直接用
	console.log(mainStore.count)
	// 使用方法2:解构
	// 注意:直接解构的数据是不具有响应式的
	// Pnina 其实就是把 state 数据都做了 reactive 处理
	// const { count , foo } = mainStore
	// 解决办法: 将数据做 ref 响应式代理
	const { count , foo } = storeToRefs(mainStore)
	console.log(count.value)
	
	// 修改store中的值
	const handleChangState = ()=>{
		// 方式一:最简单的方式
		mainStore.count++
		mainStore.foo = 'hello'
		// 方式二:如果需要修护多个数据,建议使用 $patch 批量更新。
		// 因为 批量更新多条数据, 视图只更新一次。单一的更新多条数据,视图会多次更新
		mainStore.$patch({
			count:mainStore.count + 1,
			foo:'hello'arr:[...mainStore.arr,4]
		})
		// 或
		mainStore.$patch(state=>{
			state.count++
			state.foo = 'hellow'
			state.arr.push(1)
		})
		// 方式三:逻辑比较多的时,可以封装到actions 做处理
		mainStore.changeState(10)
	}
	
  	</script>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值