当body改变时如何防止在nuxt3中执行useFetch

问题描述 投票:0回答:3

场景:

  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();
}

和模板

    <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>

不幸的是,即使我不单击按钮,每次用户在此表单中键入字母时,此表单都会向

post
发送
/api/auth/local
请求。

文档中描述了此行为:

https://nuxt.com/docs/api/composables/use-fetch

所有获取选项都可以指定一个计算值或参考值。这些将被监视,并在更新时使用任何新值自动发出新请求。

我需要覆盖此功能。

改变

v-model

v-model.lazy

有一点帮助,但我仍然无法控制发送此请求的确切时间。


我目前的解决方法

const body = ref<{ identifier: string, password: string }>({
  identifier: '[email protected]',
  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();
}

还不够好,因为它实际上同时发送了 2 个请求,但第一个请求立即被取消。

nuxt.js hook nuxtjs3
3个回答
7
投票

我也遇到同样的情况。您可以使用

{...loginbody}
取消引用 useFetch() 的选项值。

const { data } = await useFetch('/login', { method: 'post', body: {...loginbody} })

0
投票

终于实现了我的目标写作功能

async function login() {
  if(JSON.stringify(loginBody.value) === JSON.stringify(body.value)) {
    await execute();
  } else {
    loginBody.value = body.value;
  }
}
当调用

login

 函数时,
请求总是执行一次。它主体改变了他的值,然后分配给
loginBody
触发请求。在其他情况下,我们通过
execute
手动执行。

有点过度设计,但很有效。


0
投票

你需要在选项中说

watch: false

查看更多这里

© www.soinside.com 2019 - 2024. All rights reserved.