如何使用 Laravel 和 Vuejs 3 消除 axios 调用?
所以我认为使用 lodash debounce 函数来延迟 axios post 调用上的用户输入会非常简单。但我无法让它发挥作用。我在搜索输入上放置了一个观察器
,称为搜索。还有一个发出发布请求的函数(searchGames
),但由于某种原因(没有错误),我无法让 debounce 内的函数触发。
起初我以为 lodash 没有安装,但我尝试了一些其他功能,它似乎可以工作 - 所以没有任何问题。我还尝试将 axios 调用包装在去抖动函数中,但仍然没有任何运气。
<template>
<Head title="Welcome" />
<div>
<input class="mb-2" type="text" v-model="search" placeholder="game name" @input="debounceSearchGames" autofocus>
<p>Search {{ search }}</p>
<p v-for="game in games">
{{ game.title }}
</p>
</div>
</template>
<script>
import { defineComponent } from 'vue'
import { Head, Link } from '@inertiajs/inertia-vue3';
export default defineComponent({
components: {
Head,
Link,
},
data(){
return {
games: null,
search: null
}
},
watch: {
search(){
_.debounce(() => {
this.searchGames(this.search)
}, 500)
// this.searchGames(this.search)
}
},
methods: {
searchGames(string){
console.log(string)
axios.post('/games', {
title: string
})
.then(response => {
this.games = response.data
})
.catch(error => {
console.log(error)
})
}
}
})
</script>
我将 Laravel 9 与 Jetstream 和 InertiaJS 堆栈结合使用。
So I thought that it would be pretty straight forward to use lodash debounce function to delay user input on a axios post call. But I cannot get it to work. I have placed a watcher
on the search input, that is called search. And a function to make the post request (searchGames
), but for some reason (no errors) I cannot get the function inside debounce to fire.
At first I thought that lodash wasn't installed, but I have tried some other functions, and it seems to be working - so nothing wrong there. I have also tried to wrap the axios call in a debounce function, but still without any luck.
<template>
<Head title="Welcome" />
<div>
<input class="mb-2" type="text" v-model="search" placeholder="game name" @input="debounceSearchGames" autofocus>
<p>Search {{ search }}</p>
<p v-for="game in games">
{{ game.title }}
</p>
</div>
</template>
<script>
import { defineComponent } from 'vue'
import { Head, Link } from '@inertiajs/inertia-vue3';
export default defineComponent({
components: {
Head,
Link,
},
data(){
return {
games: null,
search: null
}
},
watch: {
search(){
_.debounce(() => {
this.searchGames(this.search)
}, 500)
// this.searchGames(this.search)
}
},
methods: {
searchGames(string){
console.log(string)
axios.post('/games', {
title: string
})
.then(response => {
this.games = response.data
})
.catch(error => {
console.log(error)
})
}
}
})
</script>
Im using Laravel 9 with Jetstream and the InertiaJS stack.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要同时使用
@input
和watch
。使用
watch
:...或
@input
:在 Composition API
watch
中:...或
@input
:You don't need both
@input
andwatch
.Either use
watch
:... or
@input
:In Composition API
watch
:... or
@input
: