Reputation: 936
I am coding a restaurant review project with Django REST and Vue.js. I use google place ID as PK for my restaurants since Google Place ID are unique and I use Google Place Autocomplete in my project.
So basically I have an autocomplete that get a restaurant Place ID whenever the user select it.
Then I want to redirect automatically to another route where I will fetch all the reviews for that restaurant with an API, (/api/restaurant_review/Google Place ID/
), using that Google Place ID.
This is my navbar component:
<template>
<div class="collapse navbar-collapse flex-row justify-content-end">
<vue-google-autocomplete
id="map"
class="form-control mr-sm-2"
placeholder="Find a restaurant"
v-on:placechanged="getAddressData"
country="fr"
types="establishment"
></vue-google-autocomplete>
</template>
<script>
import VueGoogleAutocomplete from "vue-google-autocomplete";
export default {
name: "NavbarComponent",
components: { VueGoogleAutocomplete },
data() {
return {
requestUser: null,
addressData: ""
};
},
created() {
this.setRequestUser();
},
methods: {
getAddressData(addressData, placeResultData) {
this.placeResultData = placeResultData;
this.addressData = addressData;
this.$router.push({ name: "reviews", params: { id : this.placeResultData.place_id }})
}
}
};
</script>
For now I made a dummy "reviews" view that only shows an "Hello World" message. Redirection is working fine but I can't find a way to check if my "id" is available in my reviews view. And I don't know if it is the right way to do so either. As well, is it possible to pass more than one params?
Upvotes: 2
Views: 5633
Reputation: 164910
As detailed in the official guide, you can define props for your route-able components (eg "review") and have Vue Router pass in any route params.
For example, in your route definition
{
name: "review",
path: "/review/:id",
component: Review,
props: true // 👈 convert path parameters like "id" to props
}
Then in your component, something like the following
export default {
props: { id: String } // 👈 passed in via the :id route parameter
async created () {
const response = await apiCall(`/api/restaurant_review/${encodeURIComponent(this.id)}`)
}
}
is it possible to pass more than one params?
Absolutely. You can define as many route parameters as you want, eg
{
path: "/my-path/:foo/:bar/:baz"
}
When using $router.push()
, you can also pass in extra params that are not part of the path. For example, using your reviews route above
this.$router.push({ name: "reviews", params: {
id: this.placeResultData.place_id,
title: this.placeResultData.name // 👈 just guessing here
}})
You can then access these via
this.$route.params.title
or define props but for these I'd recommend making them optional since they won't come from the path and therefore can't come from direct linking
props: {
fromPath: String, // from path and required
optionalParam: {
required: false,
default: "Some default value
}
}
Upvotes: 3