Incorporating Vue.js 2.6 with the vue-router
component has been quite a journey for me. My search form setup looks like this:
<form class="search-form" @submit.prevent="search">
<div class="form-group">
<input type="text" class="form-control" v-model="term" placeholder="Search">
</div>
</form>
Below is my script implementation:
<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>
The main goal of my code is to accomplish the following tasks:
- User submits the form, which triggers the
search()
function. The URL gets updated with the query parameter, for example,/search?term=<term>
. However, I am facing an issue where thesearch()
function runs twice in this scenario. - User conducts multiple searches and then clicks the back button. The search field updates in the form automatically and initiates the search. Similar to the first point, the
search()
function seems to run twice here as well. - User manually inserts a query parameter in the URL bar. The search field in the form populates accordingly and executes the search successfully. This functionality is working seamlessly.
The repeated execution of the search()
function stems from the watch()
method, responsible for monitoring changes in the URL bar. However, merging this mechanism effectively with the search()
function remains a challenge for me.