我无法在Vue JS中移动其他路径

时间:2019-09-28 11:34:19

标签: vue.js frontend vue-router

我是Vue JS的新手,并且正在Vue JS中制作一个简单的页面。这是我的代码:

main.js

import Vue from 'vue'
import App from './App.vue'
import PokeProfile from './components/PokeProfile.vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import VueRouter from 'vue-router';

Vue.use(VueRouter)
Vue.use(ElementUI)

const router = new VueRouter({
  routes: [
    {path: '/', component: App},
    {path: '/pokemon/:id', component: PokeProfile},
  ],
  mode: 'history'
})

//Vue.config.productionTip = false

new Vue({
  el: '#app',
  render: h => h(App),
  router: router
})

App.js

<template>
  <div id="app">
    <div class="tag-group">
      <el-tag
          v-for="pokemon in pokemons"
          :key="pokemon.national_id"
          :type="pokemon.name"
          effect="plain">
          <poke-item :pokemon=pokemon></poke-item>
        </el-tag>
    </div>
  </div>
</template>

<script>
import PokeItem from './components/PokeItem.vue'
import axios from 'axios'

export default {
  name: 'app',
  components: {
    PokeItem
  },
  data() {
    return {
      pokemons: []
    }
  },
  created() {
    axios.get("http://localhost:3000")
    .then(res => this.pokemons = res.data)
    .catch(err => {console.log(err)})
  }
}
</script>

<style>
div {
    display: flex;
    justify-content: center;
}
</style>

PokeItem.js

<template>
    <div>
      <router-link :to="pokemonLink">
        {{pokemon.name}}
      </router-link>
    </div>
</template>

<script>
export default {
    data() {
        return {}
    },
    props: {
        pokemon: {
            type: Object,
            required: true
        }
    },
    computed: {
        pokemonLink() {
            return `/pokemon/${this.pokemon.national_id}`
        }
    }
}
</script>

PokeProfile.js

<template>
    <h1>Hello Pokemon</h1>
</template>
<script>
export default {
}
</script>

这里的问题是,当我单击PokeItem.js文件中的项目时,我无法移至PokeProfile.js。可能是什么问题呢?我已经检查了与路由相关的代码部分,但没有发现任何问题。

1 个答案:

答案 0 :(得分:2)

Vue-Router使用动态组件(<router-view>)来呈现路线的组件。通常,您会在app.vue的模板中找到此组件。由于您没有<router-view>组件,因此Vue-Router不知道在何处呈现您的路由组件。

尝试:

// main.js

import Home from './components/Home.vue'

const router = new VueRouter({
  routes: [
    {path: '/', component: Home},
    {path: '/pokemon/:id', component: PokeProfile},
  ],
  mode: 'history'
})

// components/Home.vue

// your old App.vue

// ./App.vue
<template>
  <main>
    <router-view></router-view>
  </main>
</template>