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

(完)
git cherry-pick 的使用
git cherry-pick 的使用,Sourcetree中使用cherry-pick
Python生成一个最简单的rss.xml
feedgen库
Xray+Nginx配置健康上网并快速搭建或迁移搭建博客站点
本文介绍Docker+Nuxt+python+mongo快速搭建,不要看首图,首图因为刚好520。
vite创建vue3项目 eslint+prettier+stylelint
eslint+prettier+stylelint配置
React一些不常用知识
记录翻阅使用
韭菜成长记2
不要以为看了几本书,就可以混黑社会了,你试过被人用枪指着头,喝完整瓶的威士忌吗?
等待你的评论