一、安装依赖

  1. yarn add vue-router

二、在App.vue

  1. <template>
  2. <div id="app">
  3. <router-view></router-view>
  4. </div>
  5. </template>

三、在routers文件夹下

  1. //index.js
  2. import Vue from 'vue';
  3. import Router from 'vue-router'
  4. import Music from '@/pages/Music.vue'
  5. import Mv from '@/pages/Mv.vue'
  6. Vue.use(Router);
  7. export default new Router({
  8. mode:"hash", //history
  9. routes:[
  10. {
  11. path:'/music',
  12. name:"music",
  13. component:Music
  14. },
  15. {
  16. path:'/mv',
  17. name:"mv",
  18. component:Mv
  19. }
  20. ]
  21. })

3.1 异步路由

  • 进入页面时才会触发路由

    1. export default new Router({
    2. mode:"hash",
    3. routes:[
    4. ...
    5. {
    6. path:"/detail",
    7. name:"detail",
    8. /* 异步路由 */
    9. component:()=>import('@/pages/Detail')
    10. }
    11. ]
    12. })

四、在main.js下

  1. import router from './routers'
  2. Vue.config.productionTip = false
  3. new Vue({
  4. router,
  5. render: h => h(App),
  6. }).$mount('#app')

五、router-link 切换

  1. //App.vue下
  2. <template>
  3. <div id="app">
  4. <div id="nav">
  5. <router-link to="/music">音乐</router-link>
  6. <router-link to="/mv">MV</router-link>
  7. </div>
  8. <router-view></router-view>
  9. </div>
  10. </template>