vue3 狀態(tài)管理 之 Pinia --- 三分鐘放棄

  1. 在項(xiàng)目中安裝 pinia 模塊,并在 main.js 中進(jìn)行導(dǎo)入和 use
import {createPinia} from "pinia"

const app = createApp(App)
app.use(createPinia())
  1. 創(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++
        }
    }
})
  1. 在任何一個(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)系


  1. 如果 想讓 數(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呢

  1. 所以, 最終我的代碼變成了這樣
// /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)系

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容