Pinia详细介绍(巨详细包括Store、State、Getter、Action、插件)

定义Store:

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

Store:

在深入研究核心概念之前,我们得知道Store是用defineStore()定义的,它的第一个参数要求是一个独一无二的名字:
import { defineStore } from 'pinia'

// 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useAlertsStore = defineStore('alerts', {
// 其他配置...
})
这个名字,也被用id,是必须传入的,Pinia将用它来连接store和devtools.为了养成习惯性的用法,将返回的函数命名为use...是一个符合组合式函数风格的约定。
defineStore()的第二个参数可接受两类值:Setup函数或Option对象。

Option Store

与Vue的选项式API类似,我们也可以传入一个带有state、actions与getters属性的Option对象
export const useCounterStore = defineStore('counter', {
 state: () => ({ count: 0 }),
 getters: {
  double: (state) => state.count * 2,
},
actions: {
    increment() {
     this.count++
     },
 },
})

你可以认为state是store的数据(data),getters是store的计算属性(computed),而actions则是方法(methods)。
为方便上手使用,Option Store 应可能直观简单。

Setup Store

也存在另一种定义store的可用语法。与Vue组合式API的setup函数相似,
我们可以传入一个函数,该函数定义了一个响应式属性和方法,并且返回一个带有我们想暴露出去的属性和方法的对象。
export const useCounterStore = defineStore('counter', () => {
 const count = ref(0)
 function increment() {
    count.value++
 }

  return { count, increment }
})

在Setup Store中:
    ·ref()就是state属性
    ·computed()就是getters
    ·function()就是actions
Setup store 比 OPtion Store 带来了更多的灵活性,因为你可以在一个store内创建监听器,并自由地使用任何组合式函数。不过,请记住,使用组合式函数会让SSR变得更加复杂。

使用Store

虽然我们前面定义了一个store,但我们使用<script setup> 调用 useStore()
(或者使用setup()函数,像所有的组件那样)之前,store实例是不会被创建的:
<script setup>
import { useCounterStore } from '@/stores/counter'
// 可以在组件中的任意位置访问 `store` 变量 
const store = useCounterStore()
</script>
你可以定义任意多的store,但为了让使用pinia的益处最大化(比如允许构建工具自动进行代码分割以及TypeScript推断),你应该在不同的文件中去定义store。
如果你还不会使用setup组件,你也可以通过映射辅助函数来使用Pinia。
一旦Store被实例化,你可以直接访问在Store的state、getters和actions中定义的任何属性。我们将在后续章节继续了解这些细节,目前自动补全将帮助你使用相关属性。
请注意,store是一个用reactive包装的对象,这意味着不需要再getters后面写.value,就像setup中的props一样,如果你写了,我们也不能解构它:
<script setup>
const store = useCounterStore()
//  这将不起作用,因为它破坏了响应性
// 这就和直接解构 `props` 一样
const { name, doubleCount } = store
name // 将始终是 "Eduardo"
doubleCount // 将始终是 0
setTimeout(() => {
store.increment()
}, 1000)
//  这样写是响应式的
//  当然你也可以直接使用 `store.doubleCount`
const doubleValue = computed(() => store.doubleCount)
</script>

为了从store中提取属性时保持其响应性,你需要使用storeTorefs()。
他将为每一个响应式属性创建引用。当你只使用soter的状态而不调用任何action时,
他会非常有用。请注意,你可以直接从store中解构action,因为他们也被绑定到store上:

<script setup>
import { storeToRefs } from 'pinia'
const store = useCounterStore()
// `name` 和 `doubleCount` 是响应式的 ref
// 同时通过插件添加的属性也会被提取为 ref
// 并且会跳过所有的 action 或非响应式 (不是 ref 或 reactive) 的属性
const { name, doubleCount } = storeToRefs(store)
// 作为 action 的 increment 可以直接解构
const { increment } = store
</script>

State

在大多数情况下,state都是你的store的核心。人们通常会县定义能代表他们APP的state。在Pinia中,state被定义为一个返回初始状态的函数。这使得Pinia可以同时支持服务端和客户端。
import { defineStore } from 'pinia'

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

TypeScript

你并不需要做太多的努力就能式你的state兼容TS。确保启用了strict,或者至少启用了noImplicitThis,pinia将自动推断您的状态类型!但是,在某些情况下,您应该帮助它进行一些转换:
const useStore = defineStore('storeId', {
state: () => {
  return {
      // 用于初始化空列表
      userList: [] as UserInfo[],
      // 用于尚未加载的数据
      user: null as UserInfo | null,
    }
},
})

interface UserInfo {
    name: string
    age: number
}
可以用一个接口定义state,并添加state()的返回值的类型。
interface State {
  userList: UserInfo[]
  user: UserInfo | null
}

const useStore = defineStore('storeId', {
  state: (): State => {
    return {
     userList: [],
     user: null,
   }
  },
})

interface UserInfo {
    name: string
    age: number
}

访问state

默认情况下,你可以通过store实例访问state,直接对其进行读写
const store = useStore()

store.count++

重置state

在Setup Stores中,需要创建自己的$reset()方法:
export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)

  function $reset() {
   count.value = 0
 }

 return { count, $reset }
})

可修改的state

如果你想修改这些state属性(例如,如果你有一个表单),
你可以使用mapWritableState()作为代替。
但注意你不能像mapState()那样传递一个函数:
import { mapWritableState } from 'pinia'
import { useCounterStore } from '../stores/counter'

export default {
 computed: {
 // 可以访问组件中的 this.count,并允许设置它。
 // this.count++
 // 与从 store.count 中读取的数据相同
 ...mapWritableState(useCounterStore, ['count'])
 // 与上述相同,但将其注册为 this.myOwnName
 ...mapWritableState(useCounterStore, {
   myOwnName: 'count',
     }),
 },
}
对于像数组这样的集合,你并不一定需要使用mapWriteableState(),mapState()也允许你调用集合上的方法,除非你想用caetTiems = []替换整个数组。

变更state

除了用store.count++ 直接改变store,你还可以调用$patch方法。它允许你用一个state的补丁对象在同一时间更改多个属性: 
store.$patch({
    count: store.count + 1,
    age: 120,
    name: 'DIO',
})
不过,用这种语法的话,有些变更真的很难实现或者很耗时:任何集合的修改(例如,像数组中添加、移除一个元素或是做splice操作)都需要你创建一个新的集合。
因此,$patch方法也接受一个函数来组合这种难以用补丁对象实现的变更。
store.$patch((state) => {
  state.items.push({ name: 'shoes', quantity: 1 })
  state.hasChanged = true
})
两种变更store方法的主要区别是,$patch()允许你将多个变更归入devtools的同一个条目中。同时请注意,直接修改state,$patch()也会出现在devtools中,而且可以进行time teavel。

替换state

你不能完全替换掉store的state,因为那样会破坏其响应性。但是,你可以patch它。
// 这实际上并没有替换`$state`
store.$state = { count: 24 }
// 在它内部调用 `$patch()`:
store.$patch({ count: 24 })
可以通过变更pinia实例的state来设置整个应用的初始state。这常用于SSR中的激活过程。
pinia.state.value = {}

订阅state

类似于Vuex的subscribe方法,你可以通过store的$Subscribe()方法侦听state及其变化。
比起普通的watch(),使用$subscribe()的好处是subscriptions在patch后只触发一次(例如,当使用上面的函数版本时)。

cartStore.$subscribe((mutation, state) => {
  // import { MutationType } from 'pinia'
  mutation.type // 'direct' | 'patch object' | 'patch function'
  // 和 cartStore.$id 一样
  mutation.storeId // 'cart'
  // 只有 mutation.type === 'patch object'的情况下才可用
  mutation.payload // 传递给 cartStore.$patch() 的补丁对象。

  // 每当状态发生变化时,将整个 state 持久化到本地存储。
  localStorage.setItem('cart', JSON.stringify(state))
})

默认情况下,state Subscription会被绑定到他们的组件上(r如果store在组件的setUP()里面)。这意味着,当该组件被卸载时,他们将被自动删除。
如果你想在组件卸载后依旧保留它们,请将{ detached: true }作为第二个参数,以将state subscription从当前组件中分离: 
<script setup>
const someStore = useSomeStore()
// 此订阅器即便在组件卸载之后仍会被保留
someStore.$subscribe(callback, { detached: true })
</script>

Getter

Getter完全等同于store的state的计算值。可以通过defineStore()中的getters属性来定义它们。推荐使用箭头函数,并且它将接受state作为第一个参数:
export const useStore = defineStore('main', {
 state: () => ({
    count: 0,
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
})
大多数时候,getter仅依赖state,不过,有时他们也可能会使用其他getter。因此,即使在使用常规函数定义getter时,
我们也可以通过this访问到整个store实例,但(在TypeScript中)必须定义返回类型。这是为了避免TypeScript的已知缺陷,不过这不影响用箭头函数定义的getter,也不会影响不使用this的getter。

export const useStore = defineStore('main', {
    state: () => ({
    count: 0,
  }),
  getters: {
    // 自动推断出返回类型是一个 number
    doubleCount(state) {
      return state.count * 2
    },
   // 返回类型**必须**明确设置
    doublePlusOne(): number {
      // 整个 store 的 自动补全和类型标注 
      return this.doubleCount + 1
    },
  },
})
然后就可以访问store实例上的getter了:
<script setup>
    import { useCounterStore } from './counterStore'
    const store = useCounterStore()
</script>
<template>
     <p>Double count is {{ store.doubleCount }}</p>
</template>

访问其他getter

与计算属性一样,你也可以组合多个getter。通过this,你可以访问到其他任何getter。
即使你没有使用TypeScript,你也可以用JSDoc来让你的IDE提示类型。
export const useStore = defineStore('main', {
  state: () => ({
    count: 0,
  }),
  getters: {
   // 类型是自动推断出来的,因为我们没有使用 `this`
    doubleCount: (state) => state.count * 2,
    // 这里我们需要自己添加类型(在 JS 中使用 JSDoc)
    // 可以用 this 来引用 getter
   /**
    * 返回 count 的值乘以 2 加 1
    *
    * @returns {number}
    */
    doubleCountPlusOne() {
     // 自动补全
     return this.doubleCount + 1
    },
  },
})

向getter传递参数

Getter只是幕后的计算属性,所以不可以向他们传递任何参数。不过,你可以从getter返回一个函数,该函数可以接受任意参数:
export const useStore = defineStore('main', {
  getters: {
    getUserById: (state) => {
      return (userId) => state.users.find((user) => user.id === userId)
    },
  },
})

并在组件中使用:

<template>
  <p>User 2: {{ getUserById(2) }}</p>
</template>

请注意,当你这样做时,getter将不再被缓存,他们只是一个被你调用的函数。不过,你可以在getter本身中缓存一些结果,虽然这种做法并不常见,但是证明表明它的性能会更好:
export const useStore = defineStore('main', {
  getters: {
   getActiveUserById(state) {
     const activeUsers = state.users.filter((user) => user.active)
     return (userId) => activeUsers.find((user) => user.id === userId)
    },
  },
})

访问其他store的getter

想要使用另一个store的getter的话,那就直接在getter内使用就好:
import { useOtherStore } from './other-store'

export const useStore = defineStore('main', {
  state: () => ({
    // ...
  }),
  getters: {
    otherGetter(state) {
      const otherStore = useOtherStore()
     return state.localData + otherStore.data
   },
  },
})

使用setup()时的用法

作为store的一个属性,你可以直接访问任何getter(与state属性完全一样):
<script setup>
const store = useCounterStore()
store.count = 3
store.doubleCount // 6
</script>

不使用setup()

可以使用前一节state中的mapState()函数来其映射为getters:
import { mapState } from 'pinia'
import { useCounterStore } from '../stores/counter'

export default {
  computed: {
    // 允许在组件中访问 this.doubleCount
    // 与从 store.doubleCount 中读取的相同
    ...mapState(useCounterStore, ['doubleCount']),
   // 与上述相同,但将其注册为 this.myOwnName
    ...mapState(useCounterStore, {
      myOwnName: 'doubleCount',
      // 你也可以写一个函数来获得对 store 的访问权
      double: store => store.doubleCount,
    }),
  },
}

Action

Action相当于组件中的method。他们可以通过defineStore()中的actions属性来定义,并且它们也是定义业务逻辑的完美选择。
export const useCounterStore = defineStore('main', {
  state: () => ({
   count: 0,
  }),
  actions: {
    increment() {
      this.count++
    },
    randomizeCounter() {
     this.count = Math.round(100 * Math.random())
    },
  },
})

类似getter,action也可以通过this访问整个store实例,并支持完整的类型标注(以及自动补全)。
不同的是,action可以是异步的,你可以在它们里面await调用任何API,以及其他action!
下面是一个使用Mande的例子。请注意,你使用什么库并不重要,只要你得到的是一个Promise,
你甚至可以(在浏览器中)使用原生fetch函数:
import { mande } from 'mande'

const api = mande('/api/users')

export const useUsers = defineStore('users', {
  state: () => ({
    userData: null,
   // ...
  }),

  actions: {
    async registerUser(login, password) {
      try {
        this.userData = await api.post({ login, password })
        showTooltip(`Welcome back ${this.userData.name}!`)
      } catch (error) {
       showTooltip(error)
       // 让表单组件显示错误
        return error
      }
    },
  },
})
你也完全可以自由地设置任何你想要地参数以及返回任何结果。当调用action时,一切类型也都是可以被自动推断出来的。
Action可以像函数或着通常意义上的方法一样被调用:
<script setup>
     const store = useCounterStore()
    // 将 action 作为 store 的方法进行调用
    store.randomizeCounter()
</script>
<template>
     <!-- 即使在模板中也可以 -->
     <button @click="store.randomizeCounter()">Randomize</button>
</template>

访问其他store的action

想要使用另一个store的话,那你直接在action中调用就好了:
import { useAuthStore } from './auth-store'

export const useSettingsStore = defineStore('settings', {
  state: () => ({
   preferences: null,
   // ...
  }),
  actions: {
    async fetchUserPreferences() {
      const auth = useAuthStore()
      if (auth.isAuthenticated) {
        this.preferences = await fetchPreferences()
      } else {
        throw new Error('User must be authenticated')
      }
    },
  },
})

订阅action

你可以通过store.$onAction()来监听action和他们的结果。传递给它的回调函数会在action本身之前执行。
after表示在promise解决之后,允许你在action解决后执行一个回调函数。同样地,OnError允许你在action抛出错误或reject时执行一个回调函数。
这些函数对于追踪运行时错误非常有用。
默认情况下,action订阅器会被绑定到添加他们地组件上(如果store在组建的setup()内)。这意味着,当该组件被卸载时,它们将被自动山粗,土狗你想在组件卸载后依旧保留它们,请将true作为第二个参数传递给action订阅器,以便将其从当前组件中分离:
<script setup>
const someStore = useSomeStore()
// 此订阅器即便在组件卸载之后仍会被保留
someStore.$onAction(callback, true)
</script>

插件

由于有了底层API地支持,Pinia store现在完全支持扩展。一下是你扩展地内容:
·为store添加新的属性
·定义store时增加新的选项
·为store增加新的方法
·包装现有的方法
·改变甚至取消action
·实现副作用,如本地存储
·仅应用插件于特定store
插件是通过pinia.use()添加到pinia实例的。最简单的例子是通过返回一个对象将一个静态属性添加到所有store。
import { createPinia } from 'pinia'

// 创建的每个 store 中都会添加一个名为 `secret` 的属性。
// 在安装此插件后,插件可以保存在不同的文件中
function SecretPiniaPlugin() {
  return { secret: 'the cake is a lie' }
}

const pinia = createPinia()
// 将该插件交给 Pinia
pinia.use(SecretPiniaPlugin)

// 在另一个文件中
const store = useStore()
store.secret // 'the cake is a lie'
这对添加全局对象很有用,如路由器、modal或toast管理器。

简介

pinia插件是一个函数,可以选择性地返回要添加到store的属性。它接收一个可选参数,即context。
export function myPiniaPlugin(context) {
  context.pinia // 用 `createPinia()` 创建的 pinia。 
  context.app // 用 `createApp()` 创建的当前应用(仅 Vue 3)。
  context.store // 该插件想扩展的 store
  context.options // 定义传给 `defineStore()` 的 store 的可选对象。
  // ...
}
然后用pinia.use()将这个函数传给pinia:
pinia.use(myPiniaPlugin)
插件只会应用于在pinia传递给应用后创建的store,否则它们不会生效。

扩展Store

你可以直接通过在一个插件中返回包含特定属性的对象来为每个store都添加上特定属性:
pinia.use(()=>({ hrllo:'world' }))
你也可以直接在store上设置该属性,但可以的话,请使用返回对象的方法,这样它们就能被devtools自动追踪到:
pinia.use(({ store }) => {
  store.hello = 'world'
})
任何由插件返回的属性都会被devtools自动追踪,所以如果你想在devtools中调试hello属性,为了使devtools能追踪到hello,
请确保在dev模式下将其添加到store._customProperties中:
// 上文示例
pinia.use(({ store }) => {
  store.hello = 'world'
  // 确保你的构建工具能处理这个问题,webpack 和 vite 在默认情况下应该能处理。
  if (process.env.NODE_ENV === 'development') {
    // 添加你在 store 中设置的键值
    store._customProperties.add('hello')
  }
})
这就是在没有 .value 的情况下你依旧可以访问所有计算属性的原因,也是它们为什么是响应式的原因。

添加新的 state

如果你想给 store 添加新的 state 属性或者在服务端渲染的激活过程中使用的属性,你必须同时在两个地方添加它。。

·在 store 上,然后你才可以用 store.myState 访问它。
·在 store.$state 上,然后你才可以在 devtools 中使用它,并且,在 SSR 时被正确序列化(serialized)。
除此之外,你肯定也会使用 ref()(或其他响应式 API),以便在不同的读取中共享相同的值:
import { toRef, ref } from 'vue'

pinia.use(({ store }) => {
  // 为了正确地处理 SSR,我们需要确保我们没有重写任何一个 
  // 现有的值
  if (!Object.prototype.hasOwnProperty(store.$state, 'hasError')) {
    // 在插件中定义 hasError,因此每个 store 都有各自的
    // hasError 状态
    const hasError = ref(false)
    // 在 `$state` 上设置变量,允许它在 SSR 期间被序列化。
    store.$state.hasError = hasError
  }
  // 我们需要将 ref 从 state 转移到 store
  // 这样的话,两种方式:store.hasError 和 store.$state.hasError 都可以访问
  // 并且共享的是同一个变量
  // 查看 https://cn.vuejs.org/api/reactivity-utilities.html#toref
  store.hasError = toRef(store.$state, 'hasError')

  // 在这种情况下,最好不要返回 `hasError`
  // 因为它将被显示在 devtools 的 `state` 部分
  // 如果我们返回它,devtools 将显示两次。
})

添加新的外部属性

当添加外部属性、第三方库的类实例或非响应式的简单值时,你应该先用 markRaw() 来包装一下它,
再将它传给 pinia。下面是一个在每个 store 中添加路由器的例子:
import { markRaw } from 'vue'
// 根据你的路由器的位置来调整
import { router } from './router'

pinia.use(({ store }) => {
  store.router = markRaw(router)
})

在插件中调用 $subscribe

你也可以在插件中使用 store.$subscribe 和 store.$onAction 。
pinia.use(({ store }) => {
  store.$subscribe(() => {
    // 响应 store 变化
  })
  store.$onAction(() => {
    // 响应 store actions
  })
})

添加新的选项

在定义 store 时,可以创建新的选项,以便在插件中使用它们。
例如,你可以创建一个 debounce 选项,允许你让任何 action 实现防抖。
defineStore('search', {
  actions: {
    searchContacts() {
      // ...
    },
 },

  // 这将在后面被一个插件读取
  debounce: {
   // 让 action searchContacts 防抖 300ms
    searchContacts: 300,
  },
})

然后,该插件可以读取该选项来包装 action,并替换原始 action:

// 使用任意防抖库
import debounce from 'lodash/debounce'

pinia.use(({ options, store }) => {
  if (options.debounce) {
    // 我们正在用新的 action 来覆盖这些 action
    return Object.keys(options.debounce).reduce((debouncedActions, action) => {
      debouncedActions[action] = debounce(
        store[action],
        options.debounce[action]
      )
      return debouncedActions
    }, {})
  }
})
注意,在使用 setup 语法时,自定义选项作为第 3 个参数传递:
defineStore(
 'search',
  () => {
    // ...
  },
  {
   // 这将在后面被一个插件读取
   debounce: {
     // 让 action searchContacts 防抖 300ms
     searchContacts: 300,
    },
  }
)

TypeScript

上述一切功能都有类型支持,所以你永远不需要使用 any 或 @ts-ignore。

标注插件类型

一个 Pinia 插件可按如下方式实现类型标注:   
import { PiniaPluginContext } from 'pinia'

export function myPiniaPlugin(context: PiniaPluginContext) {
  // ...
}

为新的 store 属性添加类型

当在 store 中添加新的属性时,你也应该扩展 PiniaCustomProperties 接口。
import 'pinia'

declare module 'pinia' {
 export interface PiniaCustomProperties {
    // 通过使用一个 setter,我们可以允许字符串和引用。
   set hello(value: string | Ref<string>)
   get hello(): string

    // 你也可以定义更简单的值
    simpleNumber: number

   // 添加路由(#adding-new-external-properties)
    router: Router
  }
}
然后,就可以安全地写入和读取它了:
pinia.use(({ store }) => {
  store.hello = 'Hola'
  store.hello = ref('Hola')

  store.simpleNumber = Math.random()
  // @ts-expect-error: we haven't typed this correctly
  store.simpleNumber = ref(Math.random())
})
PiniaCustomProperties 是一个通用类型,允许你引用 store 的属性。
思考一下这个例子,如果把初始选项复制成 $options(这只对 option store 有效),如何标注类型:
pinia.use(({ options }) => ({ $options: options }))
我们可以通过使用 PiniaCustomProperties 的4种通用类型来标注类型:
import 'pinia'

declare module 'pinia' {
  export interface PiniaCustomProperties<Id, S, G, A> {
    $options: {
      id: Id
      state?: () => S
     getters?: G
      actions?: A
   }
  }
}

为新的 state 添加类型

当添加新的 state 属性(包括 store 和 store.$state )时,你需要将类型添加到 PiniaCustomStateProperties 中。
与 PiniaCustomProperties 不同的是,它只接收 State 泛型:
import 'pinia'

declare module 'pinia' {
  export interface PiniaCustomStateProperties<S> {
    hello: string
  }
}

为新的定义选项添加类型

当为 defineStore() 创建新选项时,你应该扩展 DefineStoreOptionsBase。与 PiniaCustomProperties 不同的是,
它只暴露了两个泛型:State 和 Store 类型,允许你限制定义选项的可用类型。例如,你可以使用 action 的名称:
import 'pinia'

declare module 'pinia' {
  export interface DefineStoreOptionsBase<S, Store> {
    // 任意 action 都允许定义一个防抖的毫秒数
   debounce?: Partial<Record<keyof StoreActions<Store>, number>>
  }
}
  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值