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

(完)
简单的讲讲vue Mixin应用
仅做记录参考
谈谈公司和工作
纯吐槽,不宜观看
四大AI工具简单比较
chatGPT3.5 文心一言 通义千问 bingAi华山论剑
vue3.2 Keepalive踩坑
vite-plugin-vue-setup-extend 插件给script标签赋值name属性,小问题花费我一天找答案
字节和心脏,只有一个能跳动。
随便谈谈
Python通过第三方平台转发邮件
完善你的博客评论系统
等待你的评论