Vue狀態(tài)管理工具Pinia的安裝與使用教程
一、環(huán)境搭建
1.創(chuàng)建項(xiàng)目
環(huán)境搭建還是沿用vite構(gòu)建項(xiàng)目的方法,不知道怎么構(gòu)建的小伙伴可以去vue專欄找找看哦~(用vite構(gòu)建vue項(xiàng)目還是非常輕量快捷的?。?qiáng)烈推薦使用?。?/strong>)
我們依然使用npm包指令來使用vite構(gòu)建項(xiàng)目,在命令行輸入以下指令即可
npm init vite
輸入后根據(jù)提示選擇vue項(xiàng)目,選擇TypeScript語言構(gòu)建項(xiàng)目即可。
2.安裝pinia
安裝pinia的方法有很多,可以用npm,可以用yarn,我們還是沿用npm包進(jìn)行安裝。
npm install pinia
在命令行輸入以上指令后,等待安裝成功即可。安裝成功后,在package.json文件中,查看下載的依賴,如果有pinia和對(duì)應(yīng)的版本號(hào),即為下載成功。
二、基本使用
創(chuàng)建完vue項(xiàng)目并且成功安裝pinia之后,我們首先要做的,一定要?jiǎng)?chuàng)建pinia實(shí)例,并將其全局掛載?。。?strong>不論是pinia還是其他的依賴,只要你需要使用,并且使用頻率很頻繁,都建議全局掛載)
1.創(chuàng)建pinia示例并掛載
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
// 創(chuàng)建pinia實(shí)例
const pinia = createPinia()
// 掛載到根實(shí)例上
createApp(App).use(pinia).mount('#app')
2.基本使用
訪問state
我們可以直接通過state.訪問
const store = useStore() store.counter++
使用getters
要注意,在pinia中,Getters和state里面不能使用相同的名字
export const useStore = defineStore('main', {
state: () => ({
counter: 0,
}),
getters: {
doubleCount: (state) => state.counter * 2,
},
})
使用actions
export const useStore = defineStore('main', {
state: () => ({
counter: 0,
}),
actions: {
increment() {
this.counter++
},
randomizeCounter() {
this.counter = Math.round(100 * Math.random())
},
},
})
3.詳細(xì)示例(詳細(xì)注解)
// store/index.ts
import { defineStore } from "pinia"
// 1.定義并導(dǎo)出容器
// 參數(shù)1:容器的ID,必須唯一,將來Pinia會(huì)把所有的容器掛載到根容器,每個(gè)容器的名字就是這里的ID
export const useMainStore = defineStore('main', {
/**
* 類似與組件的data, 用來存儲(chǔ)全局狀態(tài)
* 1.必須是函數(shù):這樣是為了在服務(wù)端渲染的時(shí)候避免交叉請(qǐng)求導(dǎo)致的數(shù)據(jù)狀態(tài)污染(客戶端其實(shí)無所謂)
* 2.必須是箭頭函數(shù):為了更好的ts類型推導(dǎo)
* 返回值:一個(gè)函數(shù),調(diào)用該函數(shù)即可得到容器實(shí)例
*/
state: () => {
return {
count: 100,
foo: 'bar',
arr: [1, 2, 3]
}
},
/**
* 類似于組件的computed,用來封裝計(jì)算屬性,有【緩存】功能
*/
getters: {
// 每個(gè)函數(shù)接受一個(gè)可選參數(shù):state狀態(tài)對(duì)象
// count10(state) {
// console.log('count10()調(diào)用了');// 具有緩存功能
// return state.count + 10
// }
// (不建議)如果不使用state而使用this,此時(shí)就不能對(duì)返回值類型做自動(dòng)推導(dǎo)了,必須手動(dòng)指定
count10(): number {
return this.count + 10
}
},
/**
* 完全類比于Vue2組件中的methods(可以直接用this),用來【封裝業(yè)務(wù)邏輯】,修改state
*/
actions: {
/**
* 注意??!不能使用箭頭函數(shù)定義actions?。∫欢ㄒ闷胀ê瘮?shù)?。。?
* why?因?yàn)榧^函數(shù)綁定了外部this
*/
changeState(num: number) {
// 可以直接使用this,像極了Vue2
// this.count++
// this.foo = 'hello'
// this.arr.push(4)
// 對(duì)于批量修改,建議使用patch做優(yōu)化
this.$patch((state) => {
state.count += num
state.foo = 'hello'
state.arr.push(4)
})
}
}
})
// 2.容器中的state
// 3.修改state
// 4.actions的使用
現(xiàn)在我們可以打開App.vue,去掉對(duì)我們沒用的東西,直接使用項(xiàng)目初始化時(shí)產(chǎn)生的HelloWorld.vue組件。
<script setup lang="ts">
import HelloWorld from './components/HelloWorld.vue'
</script>
<template>
<HelloWorld />
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
下面是HelloWorld.vue中的內(nèi)容:
<template>
<p>{{ mainStore.count }}</p>
<p>{{ mainStore.foo }}</p>
<p>{{ mainStore.arr }}</p>
<p>{{ mainStore.count10 }}</p>
<p>{{ mainStore.count10 }}</p>
<p>{{ mainStore.count10 }}</p>
<hr />
<p>{{ count }}</p>
<p>{{ foo }}</p>
<p>
<button @click="handleChangeState">修改數(shù)據(jù)</button>
</p>
</template>
<script lang="ts" setup>
import { storeToRefs } from 'pinia'
import { useMainStore } from '../store'
// 【哪里使用寫哪里】,此時(shí)要在HelloWorld組件中用,那就寫這里。這很Composition API
const mainStore = useMainStore()
// 禁止!這樣會(huì)喪失響應(yīng)性,因?yàn)閜inia在底層將state用reactive做了處理
// const { count, foo } = mainStore
// 解決方案:將結(jié)構(gòu)出的數(shù)據(jù)做ref響應(yīng)式代理
const { count, foo } = storeToRefs(mainStore)
const handleChangeState = () => {
// ==============數(shù)據(jù)修改的幾種方式=============
// 方式一:直接修改
// mainStore.count++
// 方式二:使用 $patch(對(duì)象) 批量修改,建議使用,底層做了性能優(yōu)化
// mainStore.$patch({
// count: mainStore.count + 1,
// foo: 'hello',
// arr: [...mainStore.arr, 4] // 這就不優(yōu)雅了,所以有了方式三
// })
// 方式三:使用 $patch(回調(diào)函數(shù)),這個(gè)更優(yōu)雅,墻裂推薦!??!
// 回調(diào)函數(shù)中的state參數(shù),就是Store定義時(shí)里面的state!
// mainStore.$patch((state) => {
// state.count++
// state.foo = 'hello'
// state.arr.push(4)
// })
// 方式四:邏輯較為復(fù)雜時(shí),應(yīng)封裝到Store的actions中,并對(duì)外暴露接口
mainStore.changeState(10)
}
</script>
以上就是關(guān)于pinia安裝和使用的知識(shí)分享,相信看完這篇文章的小伙伴們一定能運(yùn)用這些方法在項(xiàng)目開發(fā)中。當(dāng)然,可能有不足的地方,歡迎大家在評(píng)論區(qū)留言指正!
到此這篇關(guān)于Vue狀態(tài)管理工具Pinia的安裝與使用的文章就介紹到這了,更多相關(guān)Vue Pinia安裝與使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue3中provide和inject作用和場(chǎng)景
Vue3中provide和inject作用和場(chǎng)景是頂層組件向任意的底層組件傳遞數(shù)據(jù)和方法,實(shí)現(xiàn)跨層組件通信,本文通過實(shí)例介紹Vue3 provide和inject的相關(guān)知識(shí),感興趣的朋友一起看看吧2023-11-11
Vue3使用postcss-px-to-viewport實(shí)現(xiàn)頁面自適應(yīng)
postcss-px-to-viewport 是一個(gè) PostCSS 插件,它可以將 px 單位轉(zhuǎn)換為視口單位,下面我們就看看如何使用postcss-px-to-viewport實(shí)現(xiàn)頁面自適應(yīng)吧2024-01-01
vue-quill-editor 自定義工具欄和自定義圖片上傳路徑操作
這篇文章主要介紹了vue-quill-editor 自定義工具欄和自定義圖片上傳路徑操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-08-08
python虛擬環(huán)境 virtualenv的簡(jiǎn)單使用
virtualenv是一個(gè)創(chuàng)建隔絕的Python環(huán)境的工具。這篇文章主要介紹了python虛擬環(huán)境 virtualenv的簡(jiǎn)單使用,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01
vue計(jì)算屬性computed--getter和setter用法
這篇文章主要介紹了vue計(jì)算屬性computed--getter和setter用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01
elementui?el-select?change事件傳參問題
這篇文章主要介紹了elementui?el-select?change事件傳參問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01
Vue2 使用 Echarts 創(chuàng)建圖表實(shí)例代碼
本篇文章主要介紹了Vue2 使用 Echarts 創(chuàng)建圖表實(shí)例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05

