首页 > 解决方案 > 如何重定向和获取 url 参数

问题描述

我有一个带有跨布局共享的搜索输入的头栏。当用户输入(keyup)一个术语时,我必须重定向到搜索页面结果:

/search?term=blah

我正在重定向传递术语,但只要用户继续输入更多字母/术语,我就无法获得该数据。只是第一学期。

搜索表单组件:

this.$router.push(`/search?term=${this.term}`)

搜索页面(nuxt)

mounted () {
   this.search(this.$route.query.term)
},
methods: {
    search (term) {
      axios.get(`https://api.com/search?search=${term}`)
        .then(res => (this.results = res.data))
    }
}

但是只有在输入第一个字母时才会调用搜索方法,因为我正在使用 keyup 事件重定向到搜索路线。如何修复此解决方案以在每个 keyup 上调用搜索方法?或者有没有更好的方法来解决这个问题?

谢谢。

标签: vue.jsurlparameters

解决方案


我建议使用类似 lodash 的 debounce ()函数,以便等到用户(可能)完成输入后再重定向。Vue 实际上在他们的watchers文档中有一个很好的例子。

如果您决定在项目中包含 lodash(它可能已经包含在内),您可以执行以下操作:

created() {
  this.debouncedSearch = _.debounce(this.search, 500)
},
methods: {
  search (term) {
    axios.get(`https://api.com/search?search=${term}`)
      .then(res => (this.results = res.data))
    }
  }
},
watch: {
  search: function(term) {
    this.debouncedSearch();
  }
}

您的搜索页面可能需要自己的搜索表单/输入,以允许用户在被重定向到搜索页面后继续优化他们的搜索。


推荐阅读