i'm trying to display {{product.title}} in my browser url , please how can i go about it
this is my json object
{
"status": true,
"product": {
"_id": "625672a8370e769a8a93a51e",
"title": "galaxy note",
"description": "Lorem ",
}
}
this is my script tag
<script>
import axios from "axios";
export default {
data() {
return {
product: []
};
},
mounted() {
axios
.get(`http://localhost:5000/api/products/${this.$route.params.id}`, {})
.then(response => {
console.log(response);
this.product = response.data.product;
})
.catch(error => {
error;
});
axios
.get(`http://localhost:5000/api/products`, {})
.then(response => {
console.log(response);
this.product = response.data.product;
})
.catch(error => {
error;
});
},
};
</script>
this is my route
{path: "/products/:id", name: "Product", component: Product},
this is how i go to the id route
<router-link :to="`/products/${product._id}`">
<img
:src="product.photo"
alt="Placeholder image"
>
</router-link>
by default it displays http://localhost:8080/products/625672a8370e769a8a93a51e in my url how can i get it to display http://localhost:8080/products/galaxy-note
CodePudding user response:
As I said you are passing id
while redirecting the page. You need pass title
key in the <router-link>
tag.
{path: "/products/:title", name: "Product", component: Product}
<router-link :to="`/products/${product.title}`">
<img
:src="product.photo"
alt="Placeholder image"
>
</router-link>
With this done, you will have this URL http://localhost:8080/products/galaxy-note
.
Make sure that whatever value you get in the title
key of the product
object, that will be appended in the URL.
Next thing to take care is when you call the API using axios in the mounted
hook in your script tag. You won't get id
in params. You will get the title
in the params object, therefore you need to update that code as well.
EDIT 1: If you are receiving value with spaces such as galaxy note and you want to have galaxy-note in the url then you might need to replace spaces
with the -
using replace function before passing it to the <router-link>
tag.