1

I have a Vue component that renders blog posts. It currently just loads a collection of posts and renders them to the UI. This all works great.

Each of these posts has a slug, i.e. the-best-post-ever.

I'd like to enable my blog component to be able to read that value (or be passed it) and render that individual post instead of the list.

So visiting the blog would be something like http://example.com/blog whereas an individual post would be http://example.com/blog/the-best-post-ever.

What's the best way of handling this?

7
  • I guess you are already familiar with router.vuejs.org? Commented Apr 4, 2020 at 7:56
  • Indeed. This is how I initially thought to deal with it but I'm still pretty new to Vue so wanted to ensure it makes sense to use this approach. Just after posting this question I found this stackoverflow.com/questions/61025195/… Commented Apr 4, 2020 at 7:58
  • Seems like the link is referring to this topic. :) But if you don't need SSR, you can use beforeRouteEnter and beforeRouteUpdate guards to fetch data with http request. Should I write you an example? Commented Apr 4, 2020 at 8:03
  • is it me or found this "link" <- is the same as this post? Commented Apr 4, 2020 at 8:04
  • Oops, this link stackoverflow.com/questions/53243924/… Commented Apr 4, 2020 at 8:04

1 Answer 1

2

So it turns out this is extremely simple.

I updated my router:

name: 'blog',
title: 'Blog',
path: '/blog/:slug?',
component: () => import(/* webpackChunkName: "blog" */ './views/Blog.vue'),
meta: {
    isMain: true,
    public: true,  // Allow access to even if not logged in
    requireAdmin: false,
},

And now in the Blog component:

mounted() {
    console.log(this.$route.params.slug);
},

I can now ping the slug off to the server API and get this post.

In my Blog component I store this in a local variable:

created() {
    this.slug = this.$route.params.slug;
},

And pass this onto the actual blog rendering component like this:

<BlogReaderComponent category="news" :slug="slug" />

The blog reader component can then simply ignore any category variable and render a single post as opposed to a collection of posts.

I switched from mounted() to created() as in order for this data to be available early enough in the life-cycle so that when the <BlogReaderComponent is created this value is properly initialised.

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

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.