【发布时间】:2023-01-07 19:57:41
【问题描述】:
每次获取数据时,我都想更改布尔值以呈现 <Loading /> 组件。
我不希望我的条件取决于数组长度。所以我决定这样做。
并且 <Loading /> 组件从不对 state.isLoading 更改做出反应。
我尝试使用 watch 来测试 this.isLoading 是否发生了变化。但是watch 从来没有记录过任何东西。
我从未见过有人使用带有原语的手表。
问题是我不知道我是否可以将 watch 与基元一起使用以及我可以使用什么来代替,比如 React 中的 useEffect。
App.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
}
}
【问题讨论】:
-
您可以使用手表任何 被动的数据,表示通过
ref(...)或reactive(...)函数调用创建的数据(前者用于原语)。所以,不,你不能看一个“裸”基元,但你应该能够将它与包装基元一起使用,就像你正在做的那样,尽管你不应该在手表中使用bool.value。应该只是bool,不是吗? -
@HovercraftFullOfEels Full Of Eels 为什么它在布尔值更改时从不记录?
-
同样,
watch(bool.value, (newBool) => {不应该是watch(bool, (newBool) => {吗?您正在观察的是反应值,而不是裸值。 -
@HovercraftFullOfEels 试过了,没有任何改变。函数,改变值运行,但 watch 不做任何事情。
-
@HovercraftFullOfEels 如果我将 bool 分配给对象
shop,它会起作用:watch(bool, (newBool) => { console.log(newBool.isLoading) }, { deep: true })
标签: vue.js vuejs2 vue-component vuejs3