v-bind:class 不适用于 Vue 3 中的脚本设置和组合 API

v-bind:class not working with script setup and the composition API in Vue 3

我正在使用 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 class 不会被应用。这是为什么?

我刚弄明白,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>

感谢此博客的作者 post,如果您想阅读更多关于 ref 和 Vue 3 中的反应性的信息。

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