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