Learning Vue by creating a movie searcher has been quite challenging.
The issue I'm facing is that I'm using the same component for different routes with path params to fetch specific information. However, when I submit a form with a query for the API search, the page doesn't reload, and the component treats it as the previous route's info.
I've tried methods like router.go() and beforeRouteUpdate, but none of them seem to work.
See below for my code:
Router.js
import Vue from "vue";
import Router from "vue-router";
import Home from "./views/Home.vue";
import Detail from "./views/Detail.vue";
Vue.use(Router);
export default new Router({
routes: [
{
path: "/",
name: "home",
component: Home
},
{
path: "/favorites",
name: "favorites",
component: Home
},
{
path: "/results/:search",
name: "results",
component: Home
},
{
path: "/detail/:id",
name: "detail",
component: Detail
}
]
});
Cards.vue This component is called by Home
<template>
<div class="cardContainer">
<Filters />
<div
v-if="$store.state.movieList.length > 0"
class="cardContainer-container"
>
<Card
v-for="(item, index) in $store.state.movieList"
:key="index"
:id="item._id"
:title="item.title"
:img="item.image"
:year="item.year"
:description="item.description"
/>
</div>
<div v-else class="cardContainer-container">
Not fun
</div>
</div>
</template>
<script>
import Card from "./Card.vue";
import Filters from "./Filters.vue";
export default {
name: "cardContainer",
components: {
Card,
Filters,
},
data() {
return {
path: this.$route.name,
params: this.$route.params.search,
};
},
beforeMount(){
console.log("path", this.path);//this works when changing with navBars Links, but not with the search button
},
beforeRouteUpdate(to, from, next){
console.log("I hope this works", to); //This doesn't work.
next();
}
};
</script>
SearchBar.vue
<template>
<form class="searchBar" v-on:submit="onSubmit">
<input type="text" v-model="search" />
<button type="submit">
Search
</button>
</form>
</template>
<script>
export default {
name: "searchBar",
data() {
return {
search: ""
};
},
methods: {
onSubmit() {
// this.$router.go(`/results/${this.search}`) //does not work
this.$router.push(`/results/${this.search}`);
this.search = "";
}
}
};
</script>
UPDATE:
Solved the issue by adding a strange watch in the cards component and using @submit.prevent="submit" when submitting the search form.
cards.vue
<script>
import Card from "./Card.vue";
import Filters from "./Filters.vue";
export default {
name: "cardContainer",
components: {
Card,
Filters,
},
data() {
return {
path: this.$route.name,
params: this.$route.params.search,
};
},
beforeMount() {
console.log("path", this.path); //dispatch
},
created() {
this.$watch(
() => this.$route.params.search,
() => {
this.params = this.$route.params.search;
//dispatch
}
);
},
};
</script>
Still looking for a cleaner solution. If you have any ideas, please share. Thank you.