一.配置路由

1、安装依赖

  1. yarn add vue-router

2、在App.vue

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

3、在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. })

4、在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')

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

二.拆分路由

1.src/utils/config.js

  1. import Vue from 'vue'
  2. import 'lib-flexible/flexible.js'
  3. import '@/assets/css/reset.css'
  4. import BsBtn from '@/components/BsBtn.vue';
  5. Vue.filter("format",function(val){
  6. if(val.length>6){
  7. val=val.slice(0,6)+"..."
  8. }
  9. return val
  10. })
  11. Vue.component('BsBtn',BsBtn)
  12. export default Vue;

2.src/main.js

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

3.main.js中引入config.js

  1. import './utils/config.js'