vue3中storeToRefs讓store中的結(jié)構(gòu)出來的數(shù)據(jù)也能變成響應(yīng)式(推薦)
更新時間:2024年09月27日 11:45:10 作者:jjw_zyfx
這篇文章主要介紹了vue3中storeToRefs讓store中的結(jié)構(gòu)出來的數(shù)據(jù)也能變成響應(yīng)式,本文通過實例代碼給大家介紹的分需要的朋友可以參考下
2、創(chuàng)建 src/stores/counter.js 文件,其內(nèi)容如下:
import {defineStore} from "pinia"; import {ref} from "vue"; export const useCounterStore = defineStore('counter',()=>{ const count = ref(0) const increment = ()=>{ count.value++ } return{ count, increment } })
3、在.vue中進行驗證
<script setup> import {useCounterStore} from "@/stores/counter.js"; import {storeToRefs} from "pinia"; const counterStore = useCounterStore() const {count} = storeToRefs( counterStore) // 注意函數(shù)不能用storeToRefs 否則結(jié)構(gòu)出來的不是響應(yīng)式 const { increment } = counterStore </script> <template> <div> <button @click="counterStore.increment">按鈕</button> </div> <h1>{{counterStore.count}}</h1> <div> <button @click="increment">按鈕</button> </div> <h1>{{count}}</h1> </template> <style scoped> </style>
實驗結(jié)果如下:
注意
const {count} = counterStore 這種方式將變量解構(gòu)出來的count不是響應(yīng)式的 const {increment } = storeToRefs( counterStore) 同樣這種方式將函數(shù)解構(gòu)出來的也不是
到此這篇關(guān)于vue3中storeToRefs讓store中的結(jié)構(gòu)出來的數(shù)據(jù)也能變成響應(yīng)式的文章就介紹到這了,更多相關(guān)vue storeToRefs響應(yīng)式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關(guān)文章
關(guān)于Vue?"__ob__:Observer"屬性的解決方案詳析
在操作數(shù)據(jù)的時候發(fā)現(xiàn),__ob__: Observer這個屬性出現(xiàn)之后,如果單獨拿數(shù)據(jù)的值,就會返回undefined,下面這篇文章主要給大家介紹了關(guān)于Vue?"__ob__:Observer"屬性的解決方案,需要的朋友可以參考下2022-11-11