Javascript Vue.js-带查询参数的搜索表单
我将Vue.js 2.6与Javascript Vue.js-带查询参数的搜索表单,javascript,vue.js,Javascript,Vue.js,我将Vue.js 2.6与Vue路由器组件一起使用。我有一个搜索表如下: <form class="search-form" @submit.prevent="search"> <div class="form-group"> <input type="text" class="form-control" v-model="term" placeholder="Search"> </div> </form>
Vue路由器
组件一起使用。我有一个搜索表如下:
<form class="search-form" @submit.prevent="search">
<div class="form-group">
<input type="text" class="form-control" v-model="term" placeholder="Search">
</div>
</form>
这是我的剧本:
<script>
export default {
data() {
return {
term: this.$route.query.term,
items: []
}
},
created() {
if (this.term != null) {
this.search()
}
},
watch: {
'$route.query.term'() {
this.term = this.$route.query.term
this.search()
}
},
methods: {
search: function () {
window.axios.get('/images/search', {
params: {
term: this.term
}
})
.then(response => {
this.$router.push({query: { 'term' : this.term}})
this.items = response.data.collection.items
})
.catch(error => {
return error
})
}
}
}
</script>
导出默认值{
数据(){
返回{
术语:此.$route.query.term,
项目:[]
}
},
创建(){
如果(this.term!=null){
this.search()
}
},
观察:{
“$route.query.term”(){
this.term=this.$route.query.term
this.search()
}
},
方法:{
搜索:函数(){
window.axios.get(“/images/search”{
参数:{
学期:这个学期
}
})
。然后(响应=>{
this.$router.push({query:{'term':this.term}})
this.items=response.data.collection.items
})
.catch(错误=>{
返回错误
})
}
}
}
我试图通过这段代码实现以下目标:
search()
函数。URL使用查询参数更新,例如/search?term=
这正在工作,但是search()
函数被调用了两次。search()
函数被调用了两次。如果两次调用
search()
函数,这是由于watch()
函数,该函数用于监视URL栏的更改。我不知道如何将此函数与search()
函数正确组合。在watch
中,您可以将新值与旧值进行比较,并且仅当新值与旧值不同时才执行搜索
watch: {
'$route.query.term'(newVal, oldVal) {
if (newVal != oldVal) {
this.term = this.$route.query.term
this.search()
}
}
},
要使第一种情况下仅调用1,您可能需要将按钮单击处理程序与真正的搜索调用分开
<script>
export default {
data() {
return {
term: this.$route.query.term,
items: []
}
},
created() {
if (this.term != null) {
this.performSearch()
}
},
watch: {
'$route.query.term': {
handler: function(newVal, oldVal) {
if (newVal != oldVal) {
this.term = this.$route.query.term
this.performSearch()
}
},
immediate: true
}
},
methods: {
search: function () {
// this is call when user click search Button
this.$router.push({query: { 'term' : this.term}})
},
performSearch() {
// perform actual searcch
window.axios.get('/images/search', {
params: {
term: this.term
}
})
.then(response => {
this.items = response.data.collection.items
})
.catch(error => {
return error
})
}
}
}
</script>
导出默认值{
数据(){
返回{
术语:此.$route.query.term,
项目:[]
}
},
创建(){
如果(this.term!=null){
这是performSearch()
}
},
观察:{
“$route.query.term”:{
处理程序:函数(newVal、oldVal){
如果(newVal!=oldVal){
this.term=this.$route.query.term
这是performSearch()
}
},
立即:对
}
},
方法:{
搜索:函数(){
//这是用户单击搜索按钮时的调用
this.$router.push({query:{'term':this.term}})
},
性能研究(){
//执行实际的searcch
window.axios.get(“/images/search”{
参数:{
学期:这个学期
}
})
。然后(响应=>{
this.items=response.data.collection.items
})
.catch(错误=>{
返回错误
})
}
}
}