- 在項(xiàng)目中安裝 pinia 模塊,并在
main.js中進(jìn)行導(dǎo)入和use
import {createPinia} from "pinia"
const app = createApp(App)
app.use(createPinia())
- 創(chuàng)建一個(gè)用來做狀態(tài)管理的js文件
// /stores/counter.js
import { defineStore } from "pinia";
export const useCounterStore = defineStore("counter" , {
state: () => {
return {
count: 6
}
},
actions: {
increment(){
this.count++
}
}
})
- 在任何一個(gè)組件中進(jìn)行使用 比如: test.vue 中
import {useCounterStore} from "@/stores/counter"
var counter = useCounterStore()
// 我們可以采用下面三種辦法來修改 count 的值
// 第一種
counter.count++
// 第二種
counter.$patch({
count: counter.count + 1
})
// 第三種
counter.increment()
// 但不管是哪一種, 只要在 非頂層作用域 進(jìn)行修改, 則不會(huì)觸發(fā)界面更新
// 比如 我們放在 定時(shí)器 或 按鈕點(diǎn)擊事件中進(jìn)行修改
// 在定時(shí)器中修改, 界面不會(huì)更新
setInterval(() => {
console.log("時(shí)間到, 開始增加。。。。")
counter.count++
counter.$patch({
count: counter.count + 1
})
counter.increment()
console.log(counter.count)
}, 1000);
// 在 按鈕 點(diǎn)擊事件 中進(jìn)行修改, 界面也不會(huì)更新
const add = ()=>{
counter.count.value++
counter.$patch({
count: counter.count + 1
})
// counter.increment()
console.log(counter.count)
}
// 注意, 頂層作用域中,修改數(shù)據(jù),界面之所以會(huì)受影響并進(jìn)行改變,
// 是因?yàn)椋?模板 template 作用域 , 和 setup 函數(shù)作用域是一樣的,
// 本人認(rèn)為 和 pinia 并沒有什么關(guān)系
- 如果 想讓 數(shù)據(jù)變成響應(yīng)式的, 則可將
/stores/countes.js文件進(jìn)行如下方式進(jìn)行數(shù)據(jù)的定義
import { defineStore } from "pinia";
import { ref } from "vue";
export const useCounterStore = defineStore("counter" ,()=>{
const count = ref(6);
function increment(){
count.value++
}
return {
count,
increment
}
})
確實(shí), 按照如上 方式進(jìn)行 count 數(shù)據(jù)的定義, 確實(shí)變成響應(yīng)式數(shù)據(jù)了, 但這跟pinia有啥關(guān)系, 這不是用了vue3的ref么, 說的不好聽點(diǎn), 單靠vue3的ref , 我不用pinia, 也可以啊, 為什么要用pinia呢
- 所以, 最終我的代碼變成了這樣
// /stores/counter.js
// 老子不用 pinia 了, 自己封裝數(shù)據(jù)挺好的
import { ref } from "vue";
export const myStore = ()=>{
const count = ref(6);
return {
count,
}
}
在組件中使用
import {myStore} from "@/stores/counter"
var data = myStore()
data.count.value++
一切都是那么的香, 跟 pinia 沒有任何關(guān)系