Austin Branham
Austin Branham

Reputation: 173

<router-link> and JSON questions using Vue.js and Vue Router

I am creating my design portfolio using Vue CLI 3. I am using <router-view> and <router-link> to navigate to my different components. The architecture of my website is very simple. I have a home page, about page, work page, and several individual project pages:

The work page consists of several links that would click through to the individual project pages. The work component is set up like so:

<template>
  <div>
    <projectLink v-for="data in projectLinkJson" />
  </div>
</template>

<script>
import projectLink from '@/components/projectLink.vue'
import json from '@/json/projectLink.json'

export default {
  name: 'work',
  data(){
    return{
      projectLinkJson: json
    }
  },
  components: {
    projectLink
  }
}
</script>

As you can see, I'm importing JSON to dynamically render the content. The projectLink component is like so:

<template>
  <router-link to='/project'>
    <div class="projectLink" v-bind:class="type">
      <h1>{{ title }}</h1>
    </div>
  </router-link>
</template>

<script>
export default {
  name: 'projectLink',
  props: {
    title: String,
    type: String
  }
}
</script>

In the component above, you can see that I have a <router-link> set to '/project'. In my routes.js file, I am just telling this route to go to my project page component. I want to use the project page component as the framework for each of my individual project pages. But how do I do this dynamically? How can I route to the same component for each project, but change the content for each individual project page? Can I do this with JSON, like I'm doing within the work component.

My guess was that I could alter the <router-link> to give it a URL query. And then serve the data based on the changing URL query

<router-link :to="{ path: 'project', query: { url }}">

Upvotes: 0

Views: 645

Answers (1)

Kyle Nunery
Kyle Nunery

Reputation: 2049

I would create a router-link like so:

<router-link :to="{ name: 'projectDetails', params: { name: projectName }}">

I would pass some type of identifier for the project in the params object. In this example I am using name but an id may be more appropriate in your case. I would recommend using a "named" route so you can change url's easier in the future.

I would then make a ProjectDetails.vue page.

I would make an entry in your router file like so:

{
    path: "/project/:name",
    name: "projectDetails",
    props: true,
    component: () =>
      import(/* webpackChunkName: "ProjectDetails"*/ "../views/ProjectDetails")
},

Upvotes: 2

Related Questions