0
votes

I am learning how to build a website using a Vue frontend and Express REST backend.

I have created new routes as follows:

/path/to/vue-client/routes/index.js

import Vue from 'vue';
import Router from 'vue-router';
import Hello from '@components/HelloWorld';
import Register from '@components/Register';

Vue.use(Router);

export default new Router({
    routes: [
        {
            path: '/',
            name: 'hello',
            component: Hello
        },
        {
            path: '/register',
            name: 'register',
            component: Register
        }        
    ]
});

/path/to/vue-client/src/components/Register.vue

<template>
  <div>
    <h1>{{ msg }}</h1>
    <p>
     This is the registration page.
    </p>
  </div>
</template>

<script>
export default {
  name: 'Register',
  props: {
    msg: String
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

Now, having made these changes, I expect that when I browse to http://localhost:8080/register, I will see the Register page displayed, however, the browser just shows the home (irrespective of what I type in the browser url bar!).

The only way I can get the register page to be shown, is to modify App.vue directly:

/path/to/vue-client/src/App.vue

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <Register msg="Welcome to Your Vue.js App"/>
  </div>
</template>

<script>
import Register from './components/Register.vue'

export default {
  name: 'app',
  components: {
    Register
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

How do I get a link to another page (implemented as a Single File Component) to work in Vue?

1
Try @/components instead of @components in the router's component imports - Dan

1 Answers

0
votes

Inside your App.vue you need to add a

<router-view></router-view>

that will render your component (in your case Hello or Register) when matching a specific route.

To generate a link inside a component and then navigate between route/component use

<router-link to="/">Go to Hello component</router-link>

cf VueJS router doc: https://router.vuejs.org/guide/#html