java 做直播網(wǎng)站排名優(yōu)化課程
系列文章目錄
第八章 Pinia
文章目錄
- 系列文章目錄
- 前言
- 一、安裝和配置:
- 二、基本使用
- 三、一個(gè)更真實(shí)的例子
前言
Pinia是Vue.js應(yīng)用程序的狀態(tài)管理庫。它提供了一種簡(jiǎn)單,輕量級(jí)的解決方案,用于在Vue應(yīng)用程序中管理和維護(hù)狀態(tài)。Pinia庫的特點(diǎn)是易于使用和集成,可以使開發(fā)者在不犧牲性能的情況下更有效地處理和維護(hù)狀態(tài)。pinia中有三個(gè)概念,分別是:state、getter、action,對(duì)應(yīng)于Vue組件中的:data、computed、methods。
一、安裝和配置:
安裝:通過命令:npm install pinia@2.1.7 ,或者在創(chuàng)建vue項(xiàng)目的時(shí)候勾選使用Pinia。
配置:在main.js中,需要?jiǎng)?chuàng)建pinia對(duì)象,并與app對(duì)象進(jìn)行綁定,示例代碼如下:
import { createApp } from 'vue'
import { createPinia } from 'pinia'import App from './App.vue'const app = createApp(App)
app.use(createPinia())
app.mount('#app')
二、基本使用
通常在src目錄下創(chuàng)建一個(gè)stores文件夾,然后在里面按需創(chuàng)建js文件。假設(shè)要?jiǎng)?chuàng)建一個(gè)用于管理counter全局變量的庫文件,那么可以創(chuàng)建counter.js文件,然后填入以下代碼:
import { defineStore } from 'pinia'export const useCounterStore = defineStore('counter', () => {const count = ref(0)function increment() {count.value++}return { count, increment }
})
或者使用選項(xiàng)式API:
import { defineStore } from 'pinia'export const useCounterStore = defineStore('counter', {state: () => {return { count: 0 }},// 也可以這樣定義// state: () => ({ count: 0 })actions: {increment() {this.count++},},
})
這樣就定義好了一個(gè)count變量,以后在組件中可以通過以下三種方式修改:
<script setup>
import { useCounterStore } from '@/stores/counter'
const counterStore = useCounterStore()
// 1. 直接修改
counterStore.count++
// 2. 使用$patch批量修改
counterStore.$patch({ count: counterStore.count + 1 })
// 3. 使用action修改
counterStore.increment()
</script>
<template><!-- 直接從 store 中訪問 state --><div>Current Count: {{ counter.count }}</div>
</template>
以上三種修改方式的應(yīng)用場(chǎng)景如下:
- 如果只要修改一個(gè)狀態(tài)變量,并且不需要額外的操作,那么推薦使用第一種方法。
- 如果要一次性修改多個(gè)狀態(tài)變量,那么推薦使用$patch方法,效率更高。
- 如果在修改狀態(tài)變量的同時(shí)要做一些額外的操作,那么推薦第三種方法。
三、一個(gè)更真實(shí)的例子
import { defineStore } from 'pinia'
export const useTodos = defineStore('todos', {state: () => ({/** @type {{ text: string, id: number, isFinished: boolean }[]} */todos: [],/** @type {'all' | 'finished' | 'unfinished'} */filter: 'all',// 類型將自動(dòng)推斷為 numbernextId: 0,}),getters: {finishedTodos(state) {return state.todos.filter((todo) => todo.isFinished)},unfinishedTodos(state) {return state.todos.filter((todo) => !todo.isFinished)},/*** @returns {{ text: string, id: number, isFinished: boolean }[]}*/filteredTodos(state) {if (this.filter === 'finished') {// 調(diào)用其他帶有自動(dòng)補(bǔ)全的 getters ?return this.finishedTodos} else if (this.filter === 'unfinished') {return this.unfinishedTodos}return this.todos},},actions: {// 接受任何數(shù)量的參數(shù),返回一個(gè) Promise 或不返回addTodo(text) {// 你可以直接變更該狀態(tài)this.todos.push({ text, id: this.nextId++, isFinished: false })},},
})