web前端全系列 教程
1839个小节阅读:2243.6k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
如果直接从 pinia
中解构数据,会丢失响应式
xxxxxxxxxx
import { defineStore, acceptHMRUpdate } from "pinia"
export const useCountStore = defineStore("count", {
state: () => {
return {
count: 10
}
},
actions: {
increment(num) {
this.count += num
},
decrement(num) {
this.count -= num
}
}
})
xxxxxxxxxx
<template>
<h3>Pinia</h3>
<p>{{ count }}</p>
<button @click="addCountHandler">增加</button>
<button @click="minCountHandler">减少</button>
</template>
<script setup>
import { useCountStore } from "../store/count"
const store = useCountStore();
const { count } = store
function addCountHandler(){
store.increment(5)
}
function minCountHandler(){
store.decrement(5)
}
</script>
上述代码,我们操作加减的时候会发现,内容根本不会发生变化,这就是我们使用解构赋值之后,失去了响应式,我们可以用 storeToRefs
来解决找个问题
xxxxxxxxxx
<template>
<h3>Pinia</h3>
<p>{{ count }}</p>
<button @click="addCountHandler">增加</button>
<button @click="minCountHandler">减少</button>
</template>
<script setup>
import { storeToRefs } from "pinia"
import { useCountStore } from "../store/count"
const store = useCountStore();
const { count } = storeToRefs(store)
function addCountHandler(){
store.increment(5)
}
function minCountHandler(){
store.decrement(5)
}
</script>