vue3+pinia的快速入門使用教程
1. pinia介紹
官網(wǎng)關(guān)于pinia的介紹
Pinia 是一個狀態(tài)管理庫,由 Vue 核心團隊維護,對 Vue 2 和 Vue 3 都可用。
現(xiàn)有用戶可能對 Vuex 更熟悉,它是 Vue 之前的官方狀態(tài)管理庫。由于 Pinia 在生態(tài)系統(tǒng)中能夠承擔(dān)相同的職責(zé)且能做得更好,因此 Vuex 現(xiàn)在處于維護模式。它仍然可以工作,但不再接受新的功能。對于新的應(yīng)用程序,建議使用 Pinia。
事實上,Pinia 這款產(chǎn)品最初是為了探索 Vuex 的下一個版本,整合了核心團隊關(guān)于 Vuex 5 的許多想法。最終,我們意識到 Pinia 已經(jīng)實現(xiàn)了我們想要在 Vuex 5 中提供的大部分內(nèi)容,因此決定將其作為新的官方推薦。
相比于 Vuex,Pinia提供了更簡潔直接的 API,并提供了組合式風(fēng)格的 API,最重要的是,在使用 TypeScript 時它提供了非常好的類型推導(dǎo)。
2. 安裝
npm install pinia --save
3. 使用
1. src文件夾下新建store/index.js
import { createPinia } from "pinia"; // 創(chuàng)建store實例 const store = createPinia(); export default store;
2. main.ts引入
import store from '@/store/index.js' const app = createApp(App); app.use(store);
3.store下新建js文件,比如userInfo.js
import { defineStore } from 'pinia' export const userStore = defineStore({ id: 'userInfo', // 命名,唯一 state: () => { return { userInfo: {} } }, actions: { setUserInfo(data) { // 可直接通過this訪問state屬性 this.userInfo = data; }, } })
4. 頁面使用
import { userStore } from "@/store/userInfo.js"; export default defineComponent({ setup() { const store = userStore(); console.log('store實例', store); return {} },
補充:存儲狀態(tài)并持久化存儲
安裝 pinia-persistedstate-plugin
npm install pinia-persistedstate-plugin
store>index.ts
import type { App } from "vue"; import { createPinia } from "pinia"; import { createPersistedState } from "pinia-persistedstate-plugin"; const store = createPinia(); store.use(createPersistedState()); export function setupStore(app: App<Element>) { app.use(store); } export { store };
二次刷新,數(shù)據(jù)用以持久化存儲。
總結(jié)
到此這篇關(guān)于vue3+pinia的快速入門使用的文章就介紹到這了,更多相關(guān)vue3+pinia使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解如何將 Vue-cli 改造成支持多頁面的 history 模式
本篇文章主要介紹了詳解如何將 Vue-cli 改造成支持多頁面的 history 模式,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11vue父組件中獲取子組件中的數(shù)據(jù)(實例講解)
下面小編就為大家?guī)硪黄獀ue父組件中獲取子組件中的數(shù)據(jù)(實例講解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09Hexo已經(jīng)看膩了,來手把手教你使用VuePress搭建個人博客
vuepress是尤大大4月12日發(fā)布的一個全新的基于vue的靜態(tài)網(wǎng)站生成器,實際上就是一個vue的spa應(yīng)用,內(nèi)置webpack,可以用來寫文檔。這篇文章給大家介紹了VuePress搭建個人博客的過程,感興趣的朋友一起看看吧2018-04-04