pinia就是vuex5
1.安裝引入
npm install pinia
2.引入與使用
store.js
//1.定義容器
import { defineStore } from 'pinia'
//參數1:容器的ID,必須唯一,將來Pinia會把所有的容器掛載到根容器
export const useStore = defineStore ('main',{
/***
*類似於組件的 data數據的 ,用來存儲全局狀態的
* 1、必須是箭頭函數
*/
state:()=>{
return {
count:100,
foo:"lcq",
arr:[1,2,3]
}
},
/***
*類似於組件的計算屬性computed,有緩存的功能
*/
getters:{
//函數接受一個可選參數:state狀態對象
//每次調用state10,都會讓count+10 並且返回結果
count10(state){
console.log('count10 調用了')
return state.count +10
},
//如果在getters中使用了this,必須手動指定返回值的類型,否則類型推導不出來
// count110():number{
// console.log('count10 調用了')
// return this.count +10
// }
},
/***
*封裝處理數據的函數(業務邏輯):修改數據
*/
actions:{
//aciton中不能使用箭頭函數,因為箭頭函數綁定外部的 this
changeState(num:number){
// this.count++
// this.foo = "hello"
// this.arr.push(4)
// this.$pathc
//建議使用
this.$patch(state =>{
state.count+=num
state.foo='hello'
state.arr.push(4)
})
}
},
})
//2.修改容器中的 state
//3.修改 state
//4. 容器中的 action 的使用
<template>
<div>
{{Store.count}}
{{Store.foo}}
{{Store.arr}}
{{Store.count10}}
</div>
</template>
<script setup>
import {useStore} from "../../../store";
import {storeToRefs} from 'pinia'
const Store=useStore();
//storeToRefs結構賦值:實現數據的響應式
//Pinia 其實就是吧 state數據都做了reactive 處理了
const {count} = storeToRefs(Store)
//數據的修改
const handleChangeState = () =>{
//方式一:
// Store.count++
// Store.foo = 'hello'
//方式二:如果需要更新多個數據,使用$patch 批量更新:實現性能優化
// Store.$patch({
// count : Store.count+1,
// foo:'hello',
// arr:[...Store.arr,4] //添加數據
// })
//方式三:$patch一個函數:批量更新,更好的性能
Store.$patch(state =>{
state.count++
state.foo='hello'
state.arr.push(4)
})
//方式四:邏輯比較多的時候,封裝到 actions中進行使用
Store.changeState(10)
}
console.log(Store.count)
</script>
<style lang='less' scoped>
</style>
3.修改數據的注意事項
修改數據時,要去調用擁有這個數據的容器里面的actons里面的函數
因為這樣子修改數據才是響應式的
