二、状态 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>
- 直接通过 state 名称更改
const change = () => {
store.name = '新name - 直接改'
}
- 通过 patch 对象式
const change = () => {
// 将需要更改的元素写下对应的新值即可
store.$patch({ name: '新name - patch对象式' })
}
- 通过 patch 函数式:通过函数式可以更方便的写入一些逻辑代码
const change = () => {
store.$patch(state => {
if (state.name !== 'name') state.name = 'name'
else state.name = '新name - patch函数式'
})
}
- 通过自身属性 $state(注意点,这里更改时会更改整个state对象)
const change = () => {
// 若 state 中有多个元素,此时,若没有进行重写则数据将全部丢失
// 譬如,state中有id值,但是下面没有写,因此id将丢失
store.$state = { name: '新name - $state' }
}
- 借助 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函数')
}