位置:- 正文

Pinia(二)了解和使用Store

编辑:rootadmin
Pinia(二)了解和使用Store StoreStore 是保存状态(state)和业务逻辑的实体, store 不应该与我们的组件绑定. 换句话说, store 就是全局状态.store 有三个关键概念, 分别是 state, getters 和 actions, 这与 Vue 组件中的 data, computed 和 methods 是相对应的概念.定义 store通过 defineStore 函数定义 store.defineStore 接收两个参数

id: 唯一的标识, string 类型. Pinia 使用 id 与开发者工具建立联系.第二个参数可以是一个函数, 也可以是一个对象.defineStore 返回一个函数, 一般约定将返回值命名为 use....第二个参数: 对象类型如果要传入对象类型作为第二个参数, 在对象中可以配置state: 状态, 即数据. 📕注意 state 是一个函数, 函数的返回值才是真正定义的数据getters: 计算属性actions: 修改状态的方法export const useCounterStore = defineStore('counter', { state: () => { return { count: 0, } }, getters: { doubleCount: (state) => { return state.count * 2; } }, actions: { increment(a: number) { this.count += a } }})第二个参数: 函数类型在函数中可以通过 ref/reactive 定义响应式数据, 通过 computed 和 watch 定义计算属性和侦听器, 再定义一些修改数据的方法, 并通过返回对象的形式将其中一些数据暴露出去.import { defineStore } from 'pinia';import { ref } from 'vue';export const useNameStore = defineStore('name', () => { const name = ref('tom'); function setName(newName: string) { name.value = newName; } return { name, setName }});使用 store

推荐整理分享Pinia(二)了解和使用Store,希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:,内容如对您有帮助,希望把文章链接给更多的朋友!

无论定义 store 时传入的参数是对象类型还是函数类型, 调用方法一致的. 我们需要在 setup() 函数或 <script setup> 中使用

import { useCounterStore } from '../store';import { useNameStore } from '../store/index2'// 第一个store: countconst store = useCounterStore();function countPlus() { store.increment(1);}// 第二个store: nameconst name1 = useNameStore();function updateName1() { name1.setName('jerry1' + Math.random())}

📕store 实例并不会被创建直到调用 useNameStore()

可以直接通过 store. 的方式访问 store 的 state, 和

<h2>{{store.count}}</h2><button @click="countPlus">countPlus</button><hr><h2>{{ name1.name }}</h2><button @click="updateName1">updateName1</button>

Pinia(二)了解和使用Store

📕注意修改数据时, 页面并没有失去响应式, 调用 isProxy 可以看出 use... 返回的结果统统都是响应式的数据

失去响应式的陷阱

如果解构 use.. 的返回值, 那么将失去响应式❗❗❗❗❗const { name, setName } = useNameStore();function updateName() { setName('jerry' + Math.random());}<h2>{{ name }}</h2><button @click="updateName">updateName</button>

storeToRefs

为了从 store 中解构出属性并且保持其响应式, 需要调用 storeToRefs. storeToRefs 将为每个响应式数据创建 ref.先看传入函数类型的 storeconst nameStore2 = storeToRefs(useNameStore());console.log('nameStore2', nameStore2)

📕注意返回的 storeToRefs 返回的对象中只有 name, 而没有 setName, 因此完整的写法应该是

const nameStore = useNameStore();const { setName } = nameStore;const { name } = storeToRefs(useNameStore());再看传入对象类型的 storeconst store = useCounterStore();const countStore2 = storeToRefs(store)console.log('countStore2', countStore2);

📕只有 state 和 getters, 没有 actions, 因此要从 useCounterStore() 的返回值中解构出 actions 中的方法

const store = useCounterStore();const { count, doubleCount } = storeToRefs(store);const { increment } = store;function countPlus1() { increment(2);}

感谢你看到这里😀

本文链接地址:https://www.jiuchutong.com/zhishi/293077.html 转载请保留说明!
下一篇链接:https://www.jiuchutong.com/zhishi/293078.html
免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

鄂ICP备2023003026号

友情链接: 武汉网站建设 电脑维修 湖南楚通运网络