vue.js - 如何重定向和获取 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 上调用搜索方法?或者有没有更好的方法来解决这个问题?
谢谢。
解决方案
我建议使用类似 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();
}
}
您的搜索页面可能需要自己的搜索表单/输入,以允许用户在被重定向到搜索页面后继续优化他们的搜索。
推荐阅读
- reactjs - React hook useState 设置不正确
- java - 如何始终在 Spring MVC 的请求映射中返回用户所在的当前页面?
- mysql - Sequelize:检查表是否存在且为空
- javascript - JS / React - 如何从一个对象内一次映射两个对象
- excel - Excel:无法平均由公式确定的空白
- scripting - 运行最后一个 Photoshop 脚本(再次)
- python - 使用数学运算在列表中迭代
- c# - 生成对象不同步
- c# - System.IdentityModel.Tokens.Jwt 版本差异
- vb.net - 如何调试/断点 Sub Main()?