【问题标题】:Having difficulty adding a second route难以添加第二条路线
【发布时间】:2021-04-13 05:48:06
【问题描述】:

所以我是 VueJs 的新手,所以请原谅我在这里犯的任何错误。我有一个简单的前端应用程序,它有两页长。有索引路线和游戏路线。游戏路线采用路径变量名称,旨在显示在屏幕上。

我已经添加了路由,导入了组件,但是每当我尝试访问 URL 时,它只会显示索引页面。有谁知道我做错了什么? 谢谢!

这是我的 index.js 文件

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
    }
  ]
})

这是我的 game.vue 文件(不完整,我只是想先加载它):

<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>

【问题讨论】:

  • 您如何访问该网址?
  • @BoussadjraBrahim 如果在 localhost 上运行,它看起来像“localhost:8080/game/bob”。
  • 您应该使用router-linkrouter.push({ path: 'your-route' }) 前往新路线,查看此处router.vuejs.org/guide/#html

标签: javascript vue.js vue-component vue-router


【解决方案1】:

您默认使用哈希模式,允许访问以# 符号为前缀的路由:

localhost:8080/#/game/bob

如果你想像localhost:8080/game/bob 一样访问它,你应该在路由器定义中添加历史模式:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 2021-08-12
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多