前言 經過上個章節的介紹,大家可以瞭解到 uni-app-數據緩存 的基本使用方法 那本章節來給大家介紹一下 uni-app-pinia存儲數據 的基本使用方法 經過我這麼多篇章的介紹,我發現大家環境比較耗時,所以在今後的文章中,我會儘量減少環境的搭建 如果某一篇的文章環境確實是不一樣的,我會在文章 ...
前言
- 經過上個章節的介紹,大家可以瞭解到 uni-app-數據緩存 的基本使用方法
- 那本章節來給大家介紹一下 uni-app-pinia存儲數據 的基本使用方法
- 經過我這麼多篇章的介紹,我發現大家環境比較耗時,所以在今後的文章中,我會儘量減少環境的搭建
- 如果某一篇的文章環境確實是不一樣的,我會在文章中說明,然後編寫對應的搭建過程
本文的由來呢,就是因為在 Vue2 中與 Vue3 中都可以使用 Vuex 來進行數據的存儲, 但是在 Vue3 出現了 Pinia,所以我就想著在 uni-app 中使用 Pinia 來進行數據的存儲。
步入正題
首先來給大家看看官方文檔吧,在文檔中找到, uni-app
-> 教程
-> vue語法
,先來看 Vue2:
可以從圖中看到,在 Vue2 當中的存儲方式只有 Vuex,然後再來看看 Vue3:
多了一個 Pinia,好,知道了這些內容之後我就來開始寫代碼編寫示例,帶大家過一遍。
- 使用 UniApp 創建的項目是內置了 Pinia,Vue2 項目暫不支持
根據官方文檔的介紹,首先我們需要搭建一個對應的目錄結構:
├── pages
├── static
└── stores
└── counter.js
├── App.vue
├── main.js
├── manifest.json
├── pages.json
└── uni.scss
就是創建一個 stores 文件夾,在該文件夾下創建對應模塊的 js 文件。
- 創建一個預設模板項目,基於 Vue3
- 創建好項目之後,首先更改 main.js,導入 pinia,註冊 pinia,導出 pinia
Pinia
配置 Pinia
導入 Pinia:
import * as Pinia from 'pinia';
註冊 Pinia:
app.use(Pinia.createPinia());
導出 Pinia:
return {
app,
// 此處必須將 Pinia 返回
Pinia,
}
使用 Pinia
首先在 stores 文件夾下,創建 counter.js,內容如下:
import {
defineStore
} from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => {
return {
count: 0
};
},
// 也可以這樣定義
// state: () => ({ count: 0 })
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
},
},
});
如上代碼通過 defineStore 定義了一個名為 counter 的 store,然後通過 state 定義了一個 count 的狀態,然後通過 actions 定義了兩個方法,分別是 increment 和 decrement,分別用來增加和減少 count 的值。
再接著在首頁頁面,添加兩個按鈕分別是增加與減少調用 store 中的方法:
<template>
<view>
{{ count }}
<button type="primary" @click="myIncrement">增加</button>
<button type="primary" @click="myDecrement">減少</button>
</view>
</template>
<script setup>
import {
useCounterStore
} from '@/stores/counter.js'
import {
storeToRefs
} from 'pinia'
const counterStore = useCounterStore()
const {
count
} = storeToRefs(counterStore)
function myIncrement() {
counterStore.increment()
}
function myDecrement() {
counterStore.decrement()
}
</script>
代碼我寫完了,先來看運行的效果,然後我在一一解釋代碼:
- 如上代碼的含義首先在 script setup 中導入了 useCounterStore,然後通過 useCounterStore 創建了一個 counterStore
- 然後通過 storeToRefs 將 counterStore 中的 count 轉換成了 ref,然後在模板中通過 {{ count }} 將 count 的值顯示出來
- 然後通過 @click 調用 myIncrement 和 myDecrement 方法,然後在 myIncrement 和 myDecrement 方法中調用了 counterStore 中的 increment 和 decrement 方法
- 然後通過 counterStore.increment() 和 counterStore.decrement() 調用了 store 中的方法
好,到這已經結束了,是不是很簡單,我就不多說了,大家可以自己去嘗試一下。
這個存儲的是全局的數據,大家還可以新建一個 one 頁面,配置一下 tabBar 在 one 頁面中從 store 中獲取 count 的值, 顯示一下即可,在首頁操作之後 one 頁面的 count 的值也會發生變化。
End
- 如果你有任何問題或建議,歡迎在下方留言,我會儘快回覆
- 如果你覺得本文對你有幫助,歡迎點贊、收藏,你的支持是我寫作的最大動力