Pinia状态管理

什么是状态管理?

理论上来说,每⼀个 Vue 组件实例都已经在“管理”它⾃⼰的响应式状态了。我们以⼀个简单的计数器组 件为例:

<script>
 export default {
 // 状态
 data() {
 return {
 count: 0
 }
 },
 // 动作
 methods: {
 increment() {
 this.count++
 }
 }
 }
</script>
<!-- 视图 -->
<template>{{ count }}</template>

它是⼀个独⽴的单元,由以下⼏个部分组成:

状态:驱动整个应⽤的数据源;

视图:对状态的⼀种声明式映射;

交互:状态根据⽤户在视图中的输⼊⽽作出相应变更的可能⽅式。 下⾯是“单向数据流”这⼀概念的简单图示:

Pinia : https://pinia.vuejs.org/zh/

pinia的简介:

1.安装:

npm i pinia
# 或者使⽤ cnpm
cnpm i pinia

Vue3中

import { createApp } from 'vue'
// 导⼊pinia
import { createPinia } from 'pinia'
import App from './App.vue'
// 创建pinia实例
const pinia = createPinia()
const app = createApp(App)
// 使⽤pinia
app.use(pinia)
app.mount('#app')

Store (如 Pinia) 是⼀个保存状态和业务逻辑的实体,它并不与你的组件树绑定。换句话说,它承载着全 局状态。它有点像⼀个永远存在的组件,每个组件都可以读取和写⼊它。它有三个概念,state、getter 和 action,我们可以假设这些概念相当于组件中的 data、 computed 和 methods。

应该在什么时候使⽤ Store? ⼀个 Store 应该包含可以在整个应⽤中访问的数据。这包括在许多地⽅使⽤的数据,例如显示在 导航栏中的⽤户信息,以及需要通过⻚⾯保存的数据,例如⼀个⾮常复杂的多步骤表单。 另⼀⽅⾯,你应该避免在 Store 中引⼊那些原本可以在组件中保存的本地数据,例如,⼀个元素 在⻚⾯中的可⻅性。

并⾮所有的应⽤都需要访问全局状态,但如果你的应⽤确实需要⼀个全局状态,那 Pinia 将使你的 开发过程更轻松。

Store

是⽤ defineStore() 定义的,它的第⼀个参数要求是⼀个独⼀⽆⼆的名字:

import { defineStore } from 'pinia'
// 你可以对 `defineStore()` 的返回值进⾏任意命名,但最好使⽤ store 的名字,同时以 `u
se` 开头且以 `Store` 结尾。(⽐如 `useUserStore`,`useCartStore`,`useProductSt
ore`)
// 第⼀个参数是你的应⽤中 Store 的唯⼀ ID。
// defineStore() 的第⼆个参数可接受两类值:Setup 函数或 Option 对象。
export const useAlertsStore = defineStore('alerts', {
 // 其他配置...
})

options的写法

import { defineStore } from 'pinia';
export const useMyStore = defineStore('myStore', {
 state: () => ({
 count: 0,
 // other state properties
 }),
 actions: {
 increment() {
 this.count++;
 },
 // other actions
 },
 getters: {
 doubleCount() {
 return this.count * 2;
 },
 // other getters
 },
});

setup的写法:
 

export const useCounterStore = defineStore('counter', () => {
 const count = ref(0)
 function increment() {
 count.value++
 }
 return { count, increment }
})

state 是你的 store 的核⼼,它有点类似Vue组件中的data,是每个Store的数据中⼼

import { defineStore } from 'pinia'
const useStore = defineStore('storeId', {
 // 为了完整类型推理,推荐使⽤箭头函数
 state: () => {
 return {
 // 所有这些属性都将⾃动推断出它们的类型
 count: 0,
 name: 'Eduardo',
 isAdmin: true,
 items: [],
 hasChanged: true,
 }
 },
})

Action 

Action 相当于vue组件中的 method。它们可以通过 defineStore() 中的 actions 属性来定义,并且 它们也是定义业务逻辑的完美选择。

export const useCounterStore = defineStore('main', {
 state: () => ({
 count: 0,
 }),
 actions: {
 increment() {
 this.count++
 },
 randomizeCounter() {
 this.count = Math.round(100 * Math.random())
 },
 },
})

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值