Skip to content
Advertisement

Having difficulty adding a second route

So I’m new to VueJs so excuse any mistakes I make here. I have a simple front end application, which is meant to be two pages long. There’s an index route and a game route. The game route takes a path variable name that is meant to be displayed on the screen.

I’ve added the route, imported the components but whenever I try accessing the URL it just displays the index page. Does anyone know what I’m doing wrong? Thanks!

Here is my index.js file

import Vue from 'vue'
import Router from 'vue-router'
import home from '@/components/home'//index
import game from '@/components/game'


Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: home
    },
    {
      path:'/game/:name',
      name:'game',
      component:game
    }
  ]
})

Here is my game.vue file (It’s incomplete, I just want to get it to load first):

<template>
<div class="container-fluid m=0 p=0">
    <div id="theGame" class="full-page p-4">
    <div class="row">
        <h1>Welcome {{route.params.name}}</h1>
    </div>

    </div>
</div> 
</template>
<script>
const choices = ['Rock','Paper','Scissors']
export default {
    data(){
        return {
            name:'game',
            yourChoice: null,
            aiChoice:null,
            yourScore:0,
            aiScore:0,
        }
    },
    methods:{
        startPlay : function(choice){
            this.yourChoice=choice;
            this.aiChoice = choices[Math.floor(Math.random()*choices.length)];
            this.gamePlay();
        },
        gamePlay: function(){
            if(this.yourChoice=='Rock' && this.aiChoice=='Scissors'){
                this.yourScore++;
            }
            else if(this.yourChoice=='Paper' && this.aiChoice=='Rock'){
                this.yourScore++;
            }
            else if(this.yourChoice=='Scissors' && this.aiChoice=='Paper'){
                this.yourScore++;
            }
            else if(this.yourChoice==this.aiChoice){
                console.log("Draw");
            }
            else{
                this.aiScore++;
            } 
        }
    }
    
}
</script>
<style scoped>

</style>

Advertisement

Answer

You’re using hash mode by default that allows to access the routes prefixed by # sign :

localhost:8080/#/game/bob

if you want to access it like localhost:8080/game/bob you should add history mode to the router definition:

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'home',
      component: home
    },
    {
      path:'/game/:name',
      name:'game',
      component:game
    }
  ]
})
Advertisement