vue3中pinia的使用方法
一、安裝Pinia
1、使用npm安裝
在項(xiàng)目目錄下,通過(guò)命令行執(zhí)行以下命令:
npm install pinia
2、在Vue應(yīng)用中使用Pinia
在main.js(或入口文件)中引入并使用Pinia。首先導(dǎo)入createPinia函數(shù)并創(chuàng)建一個(gè)Pinia實(shí)例,然后將其掛載到Vue應(yīng)用上。
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
1、定義一個(gè)簡(jiǎn)單的store
創(chuàng)建一個(gè)新的 .js 文件(例如store.js)來(lái)定義store。
import { defineStore } from 'pinia';
// 第一個(gè)參數(shù)是store的唯一ID,第二個(gè)參數(shù)是一個(gè)函數(shù),返回store的配置對(duì)象
export const useCounterStore = defineStore('counter', {
// 類(lèi)似于Vuex中的state,存儲(chǔ)數(shù)據(jù)
state: () => {
return {
count: 0
};
},
// 類(lèi)似于Vuex中的getters,用于派生數(shù)據(jù)
getters: {
doubleCount: (state) => {
return state.count * 2;
}
},
// 類(lèi)似于Vuex中的actions和mutations的組合,用于修改state
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
}
}
});
三、在組件中使用store
1、在組件中獲取store實(shí)例并使用數(shù)據(jù)
在Vue組件中,可以使用useCounterStore函數(shù)來(lái)獲取store實(shí)例。
<template>
<div>
<p>當(dāng)前計(jì)數(shù): {{ counter.count }}</p>
<p>雙倍計(jì)數(shù): {{ counter.doubleCount }}</p>
<button @click="counter.increment()">增加計(jì)數(shù)</button>
<button @click="counter.decrement()">減少計(jì)數(shù)</button>
</div>
</template>
<script>
import { useCounterStore } from './store.js';
export default {
setup() {
const counter = useCounterStore();
return { counter };
}
};
</script>
2、在組件外使用store(例如在路由守衛(wèi)等非組件代碼中)
可以直接導(dǎo)入store定義并使用。
import { useCounterStore } from './store.js';
const counterStore = useCounterStore();
console.log(counterStore.count);
counterStore.increment();
Pinia提供了一種簡(jiǎn)潔、直觀的方式來(lái)管理Vue 3應(yīng)用中的狀態(tài),相比于Vuex,它具有更簡(jiǎn)單的API和更好的類(lèi)型支持等優(yōu)點(diǎn)。
到此這篇關(guān)于vue3中pinia的使用方法的文章就介紹到這了,更多相關(guān)vue3 pinia內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue?頂部消息橫向滾動(dòng)通知效果實(shí)現(xiàn)
系統(tǒng)頂部展示一個(gè)橫向滾動(dòng)的消息通知,就是消息內(nèi)容從右往左一直滾動(dòng),這篇文章主要介紹了vue頂部消息橫向滾動(dòng)通知,需要的朋友可以參考下2024-02-02
VUE element-ui 寫(xiě)個(gè)復(fù)用Table組件的示例代碼
本篇文章主要介紹了VUE element-ui 寫(xiě)個(gè)復(fù)用Table組件的示例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11
解決vue中對(duì)象屬性改變視圖不更新的問(wèn)題
下面小編就為大家分享一篇解決vue中對(duì)象屬性改變視圖不更新的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-02-02
解決vue組件銷(xiāo)毀之后計(jì)時(shí)器繼續(xù)執(zhí)行的問(wèn)題
這篇文章主要介紹了解決vue組件銷(xiāo)毀之后計(jì)時(shí)器繼續(xù)執(zhí)行的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07
基于 Vue.js 之 iView UI 框架非工程化實(shí)踐記錄(推薦)
為了快速體驗(yàn) MVVM 模式,我選擇了非工程化方式來(lái)起步,并選擇使用 Vue.js,以及基于它構(gòu)建的 iView UI 框架。本文給大家分享基于 Vue.js 之 iView UI 框架非工程化實(shí)踐記錄,需要的朋友參考下吧2017-11-11

