【小白鲨笔记】Pinia(二)

二、状态 State

状态(state)是 pinia 最核心的元素。它被用于记录各个组件之间需要用到的属性,存储的是函数的返回值(官方推荐箭头函数),记录的则是每个元素最初始的状态(可以于Vue中的data属性做一个对比)。

如何定义在上一篇中也有提到,这里也简单的定义一下。

import { defineStore } from 'pinia'

const useStore = defineStore('storeId', {
  state: () => { return { name = 'store' } },
})

在 store 定义完之后就可以在各个组件中使用了。这里示范一下。

<script setup lang="ts">
import { useStore } from './store'; // 引入store
import { storeToRefs } from 'pinia'; // 引入storeToRefs(用于结构赋值)

const store = useStore(); // store实例化

// 若直接使用结构赋值的方式是不具备响应式的
// 可以使用官方提供的api转为响应式:storeToRefs
const { name } = storeToRefs(store);
console.log(name);
</script>

<template>
  <div>
    store: {{ store.name }}
  </div>
</template>
更新 state 数据

总共有 5 种不同的方式,都可以更改 state 中存储的信息。在这之前,为了更方便演示,可以将其渲染到页面上。在 App.vue 中的模板中可以插入:

// 模拟更新信息:可以在组件上安装一个change按钮
<template>
	<p> state: {{ state.name }}</p>
	<button @click='change'> 更新 state </button>
</template>
<script setup lang='ts'>
	import { useStore } from './store'
	const store = useStore()
// ... 以下的五种方法
</scirpt>
  1. 直接通过 state 名称更改
const change = () => {
	store.name = '新name - 直接改'
}
  1. 通过 patch 对象式
const change = () => {
	// 将需要更改的元素写下对应的新值即可
	store.$patch({ name: '新name - patch对象式' })
}
  1. 通过 patch 函数式:通过函数式可以更方便的写入一些逻辑代码
const change = () => {
	store.$patch(state => {
		if (state.name !== 'name') state.name = 'name'
		else state.name = '新name - patch函数式'
	})
}
  1. 通过自身属性 $state(注意点,这里更改时会更改整个state对象)
const change = () => {
	// 若 state 中有多个元素,此时,若没有进行重写则数据将全部丢失
	// 譬如,state中有id值,但是下面没有写,因此id将丢失
	store.$state = { name: '新name - $state' }
}
  1. 借助 actions 函数:需要现在 store 中定义好对应的 action 函数
// 文件:store/index.ts
export const useStore = defineStore('storeId', {
	state: () => { name: 'name' },
	actions: { changeName(newName) { this.name = newName} }
})
// 文件:App.vue
const change = () => {
	store.changeName('新name - actions函数')
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值