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')
    },
  },
})

四个注意点:

  1. state 使用函数返回一个状态;
  2. getters 使用了 this,需要手动声明返回值类型;
  3. actions 使用 this 访问状态和 getters。actions可以是异步的,不再有 mutations;
  4. getters 和 actions 不使用箭头函数,否则 this 会指向 window,而不是 state。
  5. 每个 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
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值