Dan*_*iel 2 hook nuxt.js nuxtjs3
设想:
这是我的代码:
const body = ref<{ identifier: string, password: string }>({
identifier: '',
password: ''
});
const {data, execute, error, pending} = await useFetch(`${config.public.baseUrl}/api/auth/local`, {
body,
lazy: true,
method: 'post',
immediate: false,
watch: [],
})
async function login() {
console.log("login");
await execute();
}
Run Code Online (Sandbox Code Playgroud)
和模板
<form @submit.prevent="login">
<label for="email">
Email
<input type="text" v-model="body.identifier">
</label>
<label for="password">
Password
<input type="password" v-model="body.password">
</label>
<button>Login</button>
</form>
Run Code Online (Sandbox Code Playgroud)
不幸的是,即使我不单击按钮,每次用户在此表单中键入字母时,该表单都会发送post
请求。/api/auth/local
文档中描述了此行为:
https://nuxt.com/docs/api/composables/use-fetch
所有获取选项都可以指定一个计算值或参考值。这些将受到监视,并在更新时使用任何新值自动发出新请求。
我需要覆盖这个功能。
的变化
v-model
Run Code Online (Sandbox Code Playgroud)
到
v-model.lazy
Run Code Online (Sandbox Code Playgroud)
有一点帮助,但我仍然无法控制发送此请求的确切时间。
我目前的解决方法
const body = ref<{ identifier: string, password: string }>({
identifier: 'user@ok.com',
password: ''
});
const loginBody = ref<{ identifier: string, password: string }>({
identifier: '',
password: ''
});
const {data, execute, error, pending} = await useFetch(`${config.public.baseUrl}/api/auth/local`, {
body: loginBody,
lazy: true,
method: 'post',
immediate: false,
watch: [],
})
async function login() {
console.log("login");
loginBody.value = body.value;
await execute();
}
Run Code Online (Sandbox Code Playgroud)
还不够好,因为它实际上同时发送了 2 个请求,但第一个请求立即被取消。
我也遇到同样的情况。您可以通过使用取消引用 useFetch() 的选项值{...loginbody}
。
const { data } = await useFetch('/login', { method: 'post', body: {...loginbody} })
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3360 次 |
最近记录: |