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中進(jìn)行驗(yàn)證
<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>實(shí)驗(yàn)結(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)文章
vue2.0實(shí)現(xiàn)列表數(shù)據(jù)增加和刪除
這篇文章主要為大家詳細(xì)介紹了vue2.0實(shí)現(xiàn)列表數(shù)據(jù)增加和刪除,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-06-06
vue通過vue-lazyload實(shí)現(xiàn)圖片懶加載的代碼詳解
這篇文章主要給大家介紹了vue通過vue-lazyload實(shí)現(xiàn)圖片懶加載,文中通過代碼示例給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-02-02
vue中解決異步交互數(shù)據(jù)出現(xiàn)延遲問題
這篇文章主要介紹了vue中解決異步交互數(shù)據(jù)出現(xiàn)延遲問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04
Vue3實(shí)現(xiàn)拖拽圖片四角調(diào)整圖片大小的示例詳解
這篇文章主要為大家詳細(xì)介紹了如何使用Vue3實(shí)現(xiàn)拖拽圖片四角調(diào)整圖片大小的效果,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-10-10

