[Vuejs]-Vue.js on render populate content dynamically via vue.router params

3👍

I can’t tell you why your code is not working because it is an incomplete example but I can walk you through a minimal working example that does what you are trying to accomplish.

The first thing you want to do, is to ensure your vue-router is configured correctly.

export default new Router({
  mode: "history",

  routes: [
    {
      path: "/",
      component: Hello
    },
    {
      path: "/dynamic/:type",
      component: DynamicParam,
      props: true
    }
  ]
});

Here I have a route configured that has a dynamic route matching with a parameter, often called a slug, with the name type. By using the : before the slug in the path, I tell vue-router that I want it to be a route parameter. I also set props: true because that enables the slug value to be provided to my DynamicParam component as a prop. This is very convenient.

My DynamicParam component looks like this:

<template>
  <div>
    <ul>
      <li v-for="t in things" :key="t">{{ t }}</li>
    </ul>
  </div>
</template>

<script>
const collectionOfThings = {
  a: ["a1", "a2", "a3"],
  b: ["b1", "b2"],
  c: [],
};

export default {
  props: ["type"],
  data() {
    return {
      things: [],
    };
  },
  watch: {
    type: {
      handler(t) {
        this.things = collectionOfThings[t];
      },
      immediate: true,
    },
  },
};
</script>

As you can see, I have a prop that matches the name of the slug available on this component. Whenever the ‘slug’ in the url changes, so will my prop. In order to react to those changes, I setup a watcher to call some bit of code. This is where you can make your fetch/axios/xhr call to get real data. But since you are temporarily loading data from a JSON file, I’m doing something similar to you here. I assign this data to a data value on the component whenever the watcher detects a change (or the first time because I have immediate: true set.

I created a codesandbox with a working demo of this: https://codesandbox.io/s/vue-routing-example-forked-zesye

PS: You’ll find people are more receptive and eager to help when a minimal example question is created to isolate the problematic code. You can read more about that here: https://stackoverflow.com/help/minimal-reproducible-example

Leave a comment