学习vue3中computed,pinia的碰到的小疑问

Snipaste_20220608_140627.jpg

先来看看官网computed使用

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
const count = ref(1) const plusOne = computed(() => count.value + 1) console.log(plusOne.value) // 2 plusOne.value++ // 错误

这个表明当我们count是响应式数据plusOne就会跟着变化。

          
  • 1
  • 2
  • 3
  • 4
let count = 1 const plusOne = computed(() => count + 1) count ++ console.log(plusOne.value) // 2

然后试了试count是一个常数,显然之后对count数字改变,plusone是不会改变的

之后以为store里的数据并非响应式,做了实验

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
<template> <div> <button @click="add">+++</button> <div>plusOne值{{ plusOne }}</div> </div> </template> <script setup lang="ts"> import { computed } from "vue"; import { GlobalStore } from "@/store"; const globalStore = GlobalStore(); const { counter } = globalStore;//破坏了响应式 console.log(counter,globalStore);//0 一个ref的对象 const plusOne = computed(() => counter + 1); const add = () => { globalStore.counter++; }; </script>

解构赋值后counter变成了一个常数,globalStore.counter变化时,plusOne的值就不会改变,上面打印的globalStore可以看出globalStore.counter是一个响应式数据的。

Snipaste_20220608_134006.jpg

因此可以将代码改成

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
<script setup lang="ts"> import { computed } from "vue"; import { GlobalStore } from "@/store"; const globalStore = GlobalStore(); const { counter } = globalStore; console.log(counter,globalStore);//0 一个ref的对象 const plusOne = computed(() => globalStore.counter + 1); const add = () => { globalStore.counter++; }; </script>

或引入storeToRefs也可解决

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
<script setup lang="ts"> import { computed } from "vue"; import { GlobalStore } from "@/store"; import { storeToRefs } from "pinia"; const globalStore = GlobalStore(); const { counter } = storeToRefs(globalStore); console.log(counter); const plusOne = computed(() => counter.value + 1); const add = () => { globalStore.counter++; }; </script>

总结

pinia给出的数据本身具有响应式,可以用来直接computed

(完)
React hooks的几个demo
忘了?没关系看demo
闲谈时间价值
无聊随便谈谈
他们说,鱼只有7秒的记忆
好像我也强不了多少吧!!!
Python 获取IP地址并通过IP查询归属地
获取ip,通过ip-api接口查询归属地,代理改变自己的归属地
双指针: 有序数组的 Two Sum(167)
在有序数组中找出两个数,使它们的和为 target。
elementPlus date-picker踩坑
关于elementPlus date-picker无法在dialog中正常显示
等待你的评论