I am currently working with Vue.js 3 and have a sample code for routing and passing parameters.
Below is the Home.vue page:
<template>
<div class="home">
<h1>
All Destinations
</h1>
<div class="destinations">
<div v-for="destination in destinations" :key="destination.name">
<router-link
:to="{ name: 'DestinationDetails', params: { id: destination.id } }"
>
<h2>{{ destination.name }}</h2>
</router-link>
<figure>
<router-link
:to="{ name: 'DestinationDetails', params: { id: destination.id } }"
>
<img
:src="require(`@/assets/${destination.image}`)"
:alt="destination.name"
/>
</router-link>
</figure>
</div>
</div>
</div>
</template>
<script>
// @ is an alias to /src
import store from "@/store.js";
export default {
name: "home",
components: {},
data() {
return {
destinations: store.destinations
};
}
};
</script>
<style scoped>
.home {
max-width: 1400px;
margin: 0 auto;
}
img {
max-width: 200px;
}
.destinations {
display: flex;
justify-content: space-between;
}
.vue-school-active-class {
color: #ab26ab;
}
</style>
Clicking on the router link will take you to the DestinationDetails page along with sending the parameter id: destination.id
Next, here is the DestinationDetails page:
<template>
<section >
<h1>
{{ destination.name }}
</h1>
<div class="destination-details">
<img
:src="require(`@/assets/${destination.image}`)"
:alt="destination.name"
/>
<p>{{destination.description}}</p>
</div>
</section>
</template>
<script>
import store from "@/store";
export default {
data() {
return {
destinationId:this.$route.params.id
};
},
computed: {
destination() {
return store.destinations.find(
destination => destination.id === this.destinationId
);
}
}
};
</script>
<style scoped>
img {
max-width: 600px;
height: auto;
width: 100%;
max-height: 400px;
}
.destination-details {
display: flex;
justify-content: space-between;
}
p {
margin: 0 40px;
font-size: 20px;
text-align: left;
}
</style>
The issue I am facing with this code is that I'm unable to store the id from the route in the destinationId variable.
When I tried to simply read the route id on a blank template page using the code below, it worked fine:
<h1> Route: {{this.$route.params.id}} </h1>
. However, storing it in the destinationId variable did not work. Can someone please help explain why this is happening?
Lastly, here is my store.js file:
export default {
destinations: [
{
name: "Brazil",
slug: "brazil",
image: "brazil.jpg",
id: 1,
description:
"all about Brazil... [insert long description here] ...turpis.",
experiences: [
{
name: "Iguaçu Falls",
slug: "iguacu-falls",
image: "iguacu-falls.jpg",
description:
"...[insert long description here]... turpis."
},
...
]
},
...
]
};