og

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

Article at   2022/06/08 06:08  Published  code  Category,viewed  32  times

Relevant tags:    Vue    前端 

Address:   https://kedong.me/article/83

Copyright Notice: Freely reproduced for non-commercial use