vue3中如何使用pinia -- pinia使用教程(一)
pinia 是一个 Vue3 的状态管理库,它的 API 设计和 Vuex 有很大的相似之处,但是它的实现方式和 Vuex 完全不同,它是基于 Vue3 的新特性 Composition API
实现的,所以它的使用方式和 Vuex 也有很大的不同。
安装
npm i pinia
使用
main.js
import {
createApp
} from 'vue'
import App from './App.vue'
import {
createPinia
} from 'pinia'
const app = createApp(App)
// NOTE 注册 pinia 插件
app.use(createPinia())
app.mount('#app')
在使用 store 之前,需要先注册 pinia 插件。
import {
useUserStore
} from '@/stores/user'
import {
createPinia
} from 'pinia'
import {
createApp
} from 'vue'
import App from './App.vue'
// ❌ fails because it's called before the pinia is created
const userStore = useUserStore()
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
// ✅ works because the pinia instance is now active
const userStore = useUserStore()
// more info https://pinia.vuejs.org/core-concepts/outside-component-usage.html
创建 store
import {
defineStore
} from 'pinia'
// 定义并导出容器
// 参数1:store id
// 参数2:选项对象
export const useCounter = defineStore('counter', {
/**
* 全局状态:使用箭头函数返回
*/
state: () => {
return {
count: 100,
age: 20,
books: ['vue', 'react', 'svelte'],
}
},
getters: {
// NOTE getters 使用了 this,需要手动声明返回值类型
booksStr(state): string {
console.log(state.books)
return this.books.join('--')
},
},
actions: {
complexChange(step: number) {
this.age += step
this.books.push('solidjs', 'lit')
},
},
})
四个注意点:
- state 使用函数返回一个状态;
- getters 使用了 this,需要手动声明返回值类型;
- actions 使用 this 访问状态和 getters。
actions
可以是异步的,不再有 mutations; - getters 和 actions 不使用箭头函数,否则 this 会指向 window,而不是 state。
- 每个 store 只注册一次,即 id 不能重复。
使用 store
<template>
<div>
<p>counter.count {
{ counter.count }}</p>
<p>count{
{ count }}</p>
<p>age:{
{ age }}</p>
<ul>
<li v-for="book in books" :key="book">{
{ book }}</li>
</ul>
<p>{
{ booksStr }}</p>
<button @click="add">+</button>
<hr />
<button @click="changeMulti">批量修改</button>
<hr />
<button @click="changeMulti2">$patch使用接收函数</button>
</div>
</template>
<script setup lang="ts">
import {
storeToRefs
} from 'pinia'
import {
useCounter,
useTodosStore
} from '@/stores'
const {
finishedTodos,
todos
} = storeToRefs(useTodosStore())
// NOTE 不要直接解构,会失去响应式
// const { count } = counter
const {
count,
age,
books,
booksStr