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响应式内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论