首页 > 解决方案 > 使用 Vue 和 Laravel 存储 AJAX 搜索结果

问题描述

我的目标是有两个输入字段,我可以在其中键入机场的三字母代码,AJAX 将运行查询以检查数据库中是否存在该机场。如果是这样,它将在输入字段下返回该机场的名称。

我设法使第一个输入起作用,但是,我有第二个输入,我想在其中搜索第二个机场,但是每当我在第二个字段中编写机场代码时,第一个搜索的结果就会被覆盖。

下面是包含两个输入字段的 Vue 组件。您知道使用相同airportSearch()方法获得两个结果的正确方法是什么吗?

<template>
    <div class="pairing-search">
        <div class="airport-input">
            <input type="text" v-model="From" @keyup="airportSearch">
            <ul v-if="Airports.length > 0">
                <li v-for="airport in Airports" :key="airport.id">{{ airport.name }}&nbsp;({{ airport.gps_code }})</li>
            </ul>
        </div>
        <div class="airport-input">
            <input type="text" v-model="To" @keyup="airportSearch">
        </div>
    </div>
</template>

<script>
    export default {
        name: "PairingSearch",
        data() {
            return {
                From: null,
                To: null,
                Airports: []
            };
        },
        methods: {
            airportSearch() {
                axios.get('/searchairport', {
                    params: { keyword: this.From }
                })
                .then(res => this.Airports = res.data)
                .catch(error => {});
            },
        }
    }
</script>

标签: ajaxlaravelvue.js

解决方案


抱歉,我不熟悉 vue,但是在阅读文档后,您可以这样做。使用参数来拆分哪个输入触发事件。然后设置不同的元素值。

<template>
    <div class="pairing-search">

        <div class="airport-input">
            <input type="text" v-model="From" @keyup="airportSearch('first')">
            <ul v-if="Airports.length > 0">
                <li v-for="airport in Airports" :key="airport.id">{{ airport.name }}&nbsp;({{ airport.gps_code }})</li>
            </ul>
        </div>

        <div class="airport-input">
            <input type="text" v-model="To" @keyup="airportSearch('second')">
        </div>

    </div>
</template>

<script>
export default {
    name: "PairingSearch",
    data() {
        return {
            From: null,
            To: null,
            Airports: []
        };
    },
    methods: {
        airportSearch(which) {
            axios.get('/searchairport', {
                    params: { keyword: this.From }
                })
                .then(function(res){
                    if(which=='first'){
                        this.Airports = res.data
                    }else if (which=='second'){
                        this.Airports2 = res.data
                    }
                })
                .catch(error => {});
        },
    }
}
</script>

推荐阅读