Home > Net >  how can i get json object data in my url in vuejs
how can i get json object data in my url in vuejs

Time:09-17

i have this json object

    blog:{
      "_id": "62567252370e769a8a93a517", 
      "title": "my trip to zanziar"
    }

i'm trying to show in my url

http://localhost:8082/blog/my-trip-to-zanziar

in my url

but i'm getting

http://localhost:8082/blog/my trip to zanziar

and its not displaying any data

this is how i go to the route

 <router-link :to="`/blog/${blog._title}`">
                
                </router-link>

this is my router

  {
    path: "/blog/:title",
  },

this is how i diplay to get the details under the title

mounted() {
    axios
      .get(`http://localhost:4000/api/blogs/${this.$route.params.title}`, {})
      .then(response => {
        console.log(response);
        this.blog = response.data.blog;
      })
      .catch(error => {
        console.log(error);
      });
  }

please how i can go about this

CodePudding user response:

use String.prototype.replaceAll() where appropriate to replace empty spaces with hyphens:

 <router-link :to="`/blog/${blog?._title?.replaceAll(' ', '-')}`" />

You might also consider making the formatted string it's own computed property if you need to perform the replacement more than once in your component.

CodePudding user response:

you should add one more property like a slug in the blog object.

this.blog = { ...blog, slug: blog.title.replaceAll(' ','-').toLowerCase()}

now, you can use the slug in the router link.

<router-link :to="`/blog/${blog.slug}`"> ... </router-link>
  • Related