vue3中storeToRefs让store中的结构出来的数据也能变成响应式(推荐)
作者:jjw_zyfx
这篇文章主要介绍了vue3中storeToRefs让store中的结构出来的数据也能变成响应式,本文通过实例代码给大家介绍的分需要的朋友可以参考下
2、创建 src/stores/counter.js 文件,其内容如下:
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)
// 注意函数不能用storeToRefs 否则结构出来的不是响应式
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>实验结果如下:

注意
const {count} = counterStore 这种方式将变量解构出来的count不是响应式的
const {increment } = storeToRefs( counterStore) 同样这种方式将函数解构出来的也不是到此这篇关于vue3中storeToRefs让store中的结构出来的数据也能变成响应式的文章就介绍到这了,更多相关vue storeToRefs响应式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
