学习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

(完)
再谈浅拷贝和深拷贝
基础要扎实
使用 cloudflare 反代 gravatar 免费生成国内镜像
国内gravatar无法直接访问,cloudflare 可以做一个自己的镜像网址
开机进入grub如何处理
grub如何引导启动系统
初读《穷查理宝典》
巴菲特合伙人查理芒格传记
React hooks的几个demo
忘了?没关系看demo
将json数据导出成xlsx格式
更多请学习sheetJS
等待你的评论