直接上代碼
const today = new Date(2019, 2, 28)
const finalDate = new Date(today)
finalDate.setDate(today.getDate() + 3)console.log(finalDate) // 31 March 2019
-
安裝
yarn add pinia
# or with npm
npm install pinia
-
創建第一個store倉庫
1、在src目錄下創建store目錄
2、創建一個 PiniaTest.ts 的文件(文件名可以根據自己需求來)
import {defineStore} from 'pinia'// 使用 defineStore 定義一個倉庫,
// 組件中需要引入倉庫,并使用useStorePinia 進行實例化
// main 是倉庫唯一的ID,可以根據自己的需求定義
export const useStorePinia = defineStore('main', {// 閉包state () {return {msg: 'hello word',count: 10,content: '這是通過getters獲取Pinia管理的倉庫數據'}},// 簡寫方式// state: () => ({// msg: 'hello word',// count: 10// }),getters:{getMsgFn(){return this.content}},actions:{// actions 里面可以執行同步和異步任務// 也可以接收外部傳遞進來的參數// 可以直接修改倉庫的值,此處不能使用箭頭函數,否則找不到this,打印顯示 undefinedchangeMsg (val) {console.log('傳入進來的值:', val)this.msg = '1111'this.count == val;}}
})
-
引入并使用步驟
-
在 main.js 里面引入pinia
-
使用 createPinia 進行實例化
-
掛載到Vue身上(實際上是將插件進行注冊,給放到已經注冊的插件數組列表中)
import { createApp } from 'vue'
// 引入inia
import {createPinia} from 'pinia'
import App from './App.vue'console.log('createPinia:', createPinia);// 創建實例
const pinia = createPinia();console.log('pinia:', pinia);// 使用插件
createApp(App).use(pinia).mount('#app')
-
Pinia在組價中的使用
<template><div style="background: pink;padding: 10px;margin: 10px 0;"><div>組件11111111111</div><div>倉庫數據:{{count}}---{{getMsgFn}}</div><button @click="changeStoreCountFn">點擊</button></div>
</template><script setup>
import {defineProps} from 'vue';
import { storeToRefs } from "pinia";// 引入倉庫
import {useStorePinia} from '../Store/PiniaTest'// 此處 defineStore 與倉庫名一樣
const store = useStorePinia();// 此處可以獲取getters 和 actions 中的函數,但是不能直接獲取倉庫中的數據,需要使用storeToRefs強轉ref類型
const {changeMsg, getMsgFn} = store;// 只有強轉ref后數據才是響應式的
const {msg, count} = storeToRefs(store);
console.log(11111, store,storeToRefs(store), msg, count)// 修改倉庫count值
const changeStoreCountFn = () => {// 方式 1、通過觸發倉庫 actions 中定義的函數執行changeMsg(++count.value)console.log(2222,getMsgFn)// 方式 2、讀取倉庫數據進行修改// count.value++// msg.value = 'aaaaaa'// 方式 3、對象形式修改倉庫數據// store.$patch({// msg: 'change word',// count: ++count.value// })// 方式 4、函數形式修改倉庫數據// store.$patch((state) =>{// state.msg = 'change word';// state.count++// })
}
</script>