-2

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%20trip%20to%20zanziar

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

i'm getting Cannot read properties of undefined (reading 'replaceAll')
your blog._title must not be fully defined at the time of component creation. that's ok. I've updated my answer to utilize optional chaining. this will prevent any errors while the blog object data is still loading.
If I remove _ it's works but it does display the data under the route
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.