我可以将 Vue 3 中的 watch 与基元一起使用吗?

问题描述 投票:0回答:3

每次获取数据时,我都想更改布尔值来渲染

<Loading />
组件。 我不希望我的条件依赖于数组长度。所以我决定这样做。 并且
<Loading />
组件永远不会对
state.isLoading
变化做出反应。 我尝试使用
this.isLoading
来测试
watch
是否发生变化。但
watch
从未记录过任何内容。 我从未见过有人使用带有基元的手表。 问题是我不知道是否可以将
watch
与原语一起使用,以及我可以使用什么来代替,就像 React 中的
useEffect
一样。

应用程序.vue

<script setup>
  import { RouterView } from 'vue-router'
  import { watch, ref, onMounted, reactive } from 'vue';
  import Navbar from './components/Navbar.vue'
  import { useShopStore } from './stores/shopStore';

  const shop = useShopStore()

  const bool = ref(shop.isLoading)

  console.log(bool)

  watch(bool.value, (newBool) => {
    console.log(newBool)
  }, { deep: true })
</script>

类别.vue

<template>
  <LoadingVue v-if="shop.isLoading" />
  <div v-else class="category__menu">
    <CardVue
      v-for="item in shop.category"
      :item="item"
      :key="item.id"
    />
  </div>
</template>

ShopStore.js

actions: {
  async getProducts(path) {
    if (typeof path !== 'string' || path === undefined) return
    this.setLoading()
    try {
      const response = fetch(`https://fakestoreapi.com/products/category/${path}`)
      .then(res => res.json())
      .then(res => this.category = res)
    } catch (error) {
      console.log(error)
      alert('Something went wrong')
    }
    this.setLoading()
  },
  setLoading() {
    console.log('setLoading')
    this.isLoading = !this.isLoading
  }
}
vue.js vuejs2 vue-component vuejs3
3个回答
2
投票

您正在根据反应数据创建新的引用。这就像按值复制一样,原始反应数据和包裹在其上的新引用没有连接。因此,当

shop.isLoading
发生变化时,您的
bool
参考不会变化,它们现在是两个不同的变量。

我猜你在商店中使用 pinia。如果是这样,则

shop.isLoading
已经是响应式的,您不必将其包装到
ref
中。

<Loading v-model="shop.isLoading" />

您还可以使用 pinia 的

storeToRefs
辅助方法对您的商店使用解构并获取您的状态的参考:

const { isLoading } = storeToRefs(shop)

console.log(isLoading.value)

0
投票

所以。 问题是我使用了

async
但我没有在函数内部使用
await
,这就是条件如此工作的原因。或者没有按照我的预期工作。 现在我修好了它,我想公开承认我是个十足的白痴。 感谢您的关注。 附: 还是没弄清楚怎么用
watch
。唯一的方法是观察整个状态对象。
watch
仅对
state.bool
值变化做出反应。


0
投票

要查看具有原始类型的变量,您可以执行如下操作

let simpleBoolean = false;
watch(
    () => simpleBoolean,
    () => console.log('simple boolean changed!', simpleBoolean)
);
© www.soinside.com 2019 - 2024. All rights reserved.