十分钟学会使用 pinia (vue 3.x)

236 阅读1分钟

pinia 文档

一:安装

yarn add pinia
# 或者使用 npm
npm install pinia

二:创建一个 pinia 实例 (根 store) 并将其传递(挂载)给应用:

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
const app = createApp(App)

app.use(pinia)
app.mount('#app')

三:定义 Store

Store 是用 defineStore() 定义的,它的第一个参数要求是一个独一无二的名字, 这个名字 ,也被用作 id ,是必须传入的, Pinia 将用它来连接 store 和 devtools。第二个参数传入一个函数来定义 Store。

import { defineStore } from 'pinia'

// 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})


四:使用 Store

<template>
  <div>{{ counterStore.count }}</div>
  <div>{{ counterStore.doubleCount }}</div>
  
  <button @click="add">count+</button>
</template>


<script setup>
import { useCounterStore } from '@/stores/counter'
 
const counterStore = useCounterStore()
// 以下三种方式都会被 devtools 跟踪
counterStore.count++
counterStore.$patch({ count: counterStore.count + 1 })
counterStore.increment()

// add, add2, add3 等价
const add = ()=>{
  counterStore.increment();
}
const add2 = ()=>{
  counterStore.$patch((state)=>{
     state.count++;
  })
}
const add3 = ()=>{
  counterStore.$patch({ count: counterStore.count + 1 })
}


</script>
 

五. 解构store

  • Pinia是不允许直接解构是会失去响应性的
<template>
  <div>{{ count }}</div>
</template>


<script setup>
import { useCounterStore } from '@/stores/counter'
 
const counterStore = useCounterStore()

const {count} = counterStore;


</script>

解决方案可以使用 storeToRefs

<template>
  <div>{{ count }}</div>
</template>


<script setup>
import { storeToRefs } from 'pinia'
import { useCounterStore } from '@/stores/counter'
 
const counterStore = useCounterStore()
const {count} = storeToRefs(counterStore);

</script>