v-bind:类不能与Vue 3中的脚本设置和组合API一起工作



我使用的是Vue 3,带有脚本设置和组合API。我来自Svelte,所以使用脚本设置真的让我想起了Svelte的简单性。

但我很困惑为什么这不起作用。

我有这个模板代码:

<template>
<form @submit.prevent="handleSignIn(email, password)">
...
<button type="submit" :class="{ 'is-loading': isLoading }">Log in</button>
...
</form>
</template>

和这个脚本代码:

<script setup lang="ts">
let email: string;
let password: string;
let isLoading: boolean;
const handleSignIn = async (email: string, password: string) => {
isLoading = true;
...
};
</script>

但是当单击表单按钮时,不会应用is-loading类。为什么呢?

我刚刚弄明白了,isLoading的性质不是反应性的

它只在组件第一次加载时呈现,但之后对变量的任何更改都不会反映在DOM中。

要修复它,我们可以import { ref } from 'vue'并使用ref(),这将标记该变量为反应数据。在Vue 3中,Vue将创建一个代理。

工作的例子:

<script setup lang="ts">
import { ref } from 'vue'
const isLoading = ref(false)
let email: string;
let password: string;
const handleSignIn = async (email: string, password: string) => {
isLoading.value = true;
...
};
</script>

感谢这篇博文的作者,如果你想了解更多关于Vue 3中的ref和反应性。

https://www.danvega.dev/blog/2020/02/12/vue3-ref-vs-reactive/

最新更新