当主体更改时,如何防止在 nuxt3 中执行 useFetch

Dan*_*iel 2 hook nuxt.js nuxtjs3

设想:

  1. 有登录页面。
  2. 我们只想在按下登录按钮时向服务器发送请求。
  3. 我们不想在用户更改输入时发送请求。

这是我的代码:

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 个请求,但第一个请求立即被取消。

vam*_*fan 7

我也遇到同样的情况。您可以通过使用取消引用 useFetch() 的选项值{...loginbody}

const { data } = await useFetch('/login', { method: 'post', body: {...loginbody} })
Run Code Online (Sandbox Code Playgroud)