【问题标题】:Vue.js live search with more than 1 parameter具有超过 1 个参数的 Vue.js 实时搜索
【发布时间】:2018-02-25 13:25:27
【问题描述】:

如何使用vue 创建实时搜索,API 中的参数为 3,即选择 1、选择 2 和文本框 1?
例如http://example.com/api/?param1=x&param2=xx&param3=xxx



【问题讨论】:

  • 这个问题太宽泛了,无法回答。如果遇到困难,请尝试并发布更具体的问题。
  • @DanielBeck 我已经编辑过了。它现在更适合您吗?

标签: laravel vue.js


【解决方案1】:

首先,您需要在 laravel 中为您的搜索创建一个端点,使用您的 3 个参数作为获取请求,如 here 所述。

其次,您需要编写 Vue 组件并使用异步请求调用该端点。最简单的方法可能是使用axios

在您的发送按钮上注册一个点击侦听器,并确保阻止默认事件,以便它不会刷新您的页面。从表单中获取所有参数并发送请求,如下所示:

  axios.get('/search?ID=12345&name=jondoe')
  .then(function (response) {
    // update your view here with the response. Example:
    this.resultTable = response.results
  })
  .catch(function (error) {
    console.log(error);
  });

【讨论】:

    【解决方案2】:

    这是完整的解决方案,除了 Vue,我还使用 axios 来处理 API 请求,并使用 loadash 来获得 vanilla js 本身不提供的额外功能。如果您使用的是 Laravel Mix,那么您已经拥有了所有这些使用 CDN 导入的其他内容

     <script src="https://unpkg.com/vue@2.0.3/dist/vue.js"></script>
     <script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script>
     <script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script>
    

    在查看页面中

    <select v-model="select1" >
            <option >1</option>
            <option >2</option>
     </select>
     <select v-model="select2" >
            <option >1</option>
            <option >2</option>
     </select>
    <input type="text" v-model="textbox">
    

    现在是主要脚本部分

    <script>
      var app = new Vue({
      el: '#app',
      data: {
        select1: '',
        select2: '',
        textbox: '',
      },
      watch: {
        textbox: function() {
          if (this.textbox.length >= 3) { 
            this.findResults();
          }
        }
      },
      methods: {
        findResults: _.debounce(function() {
          self = this;
          axios.post('your laravel post url',{
                    select1 : self.select1,
                    select2 : self.select2,
                    textbox : self.textbox,
                })
                .then(function (response) {
                    console.log(response.data);
                })
                .catch(function (error) {
                    console.log(error);
                })
        }, 500)
      }
    })
    </script>
    

    我不包括服务器端部分,您只需返回查询对象而不转换为 JSON。

    注意,我使用 watch 来防止在用户至少输入一些字母之前调用 findResult 函数。

    loadash debounce函数用于延迟API请求500秒,防止频繁请求。

    我假设您知道如何使用 v-for 指令输出返回查询对象。如果你不知道下面的评论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 2016-05-19
      • 2015-10-15
      • 1970-01-01
      • 2015-07-19
      • 2015-05-17
      • 1970-01-01
      相关资源
      最近更新 更多