下面 POST 请求的请求负载就在网络选项卡中的
{"email":""}
。
当我在请求正文中硬编码 email.value 时,它可以工作,但它似乎没有从 v-model 中获取值。
<form @submit.prevent="notifyMe" class="mt-10 max-w-md">
<div class="flex gap-x-4">
<label for="email-address" class="sr-only"
>Email address</label
>
<input
v-model="email"
id="email"
name="email"
type="email"
autocomplete="email"
required
class="min-w-0 flex-auto rounded-md border-0 px-3.5 py-2 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-1 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"
placeholder="Enter your email"
/>
<button
:disabled="pending"
type="submit"
class="disabled:bg-indigo-400 inline-flex items-center gap-x-2 rounded-md bg-indigo-600 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
>
Notify me
<ButtonSpinner v-show="pending" />
</button>
</div>
</form>
<script setup>
const config = useRuntimeConfig();
const email = ref("");
const notifyMe = () => {
// Make the useFetch API call below
return execute();
};
const { pending, execute } = useFetch("/notifyme", {
immediate: false,
baseURL: config.public.apiBase,
method: "POST",
body: {
email: email.value,
},
});
</script>
我通常使用这种方法,它对我有用:
<template>
<form @submit.prevent="submitForm" class="mt-10 max-w-md">
<!-- ... your input field and button ... -->
</form>
</template>
<script setup>
import { ref } from "vue";
import { useFetch } from "@nuxt/http";
const email = ref("");
const { pending, execute } = useFetch("/notifyme", {
immediate: false,
baseURL: config.public.apiBase,
method: "POST",
});
const submitForm = () => {
execute({ email: email.value });
};
</script>