1.以vue-router导航守卫的使用为例

1.router.js

import Vue from 'vue'
import Router from 'vue-router'
import Login from './views/Login'
import StudentLayout from '@/layout/Student'
import TeacherLayout from '@/layout/Teacher'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  // base: '/api/',
  routes: [
    {
      path: '/',
      name: 'login',
      component: Login
    }, {
      path: '/student',
      component: StudentLayout,
      children: [
        {
          path: 'index',
          component: () => import('@/views/student/Index.vue'),
          // name: 'Index',
          meta: { title: '学生主页' }
        }, {
          path: 'record',
          component: () => import('@/views/student/Record.vue'),
          // name: 'Record',
          meta: { title: '考试记录' }
        }
      ]
    },
    { path: '*', name: '*', component: () => import('@/views/error-page/404'), meta: { title: '404' } }
  ]
})

export { router }

2.main.js

import Vue from 'vue'
import './plugins/axios'
import App from './App.vue'
// import router from './router'
import { router } from './router'
import qs from 'qs'
import './plugins/element.js'

Vue.config.productionTip = false

axios.defaults.baseURL = 'http://localhost:8080/api';

Vue.prototype.qs = qs

router.beforeEach((to, from, next) => {
  /* 路由发生变化修改页面meta */
  if (to.meta.content) {
    let head = document.getElementsByTagName('head');
    let meta = document.createElement('meta');
    meta.content = to.meta.content;
    head[0].appendChild(meta)
  }
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title;
  }
  next()
})

new Vue({
  router,
  render: function (h) { return h(App) }
}).$mount('#app')

2.console

Uncaught TypeError: Cannot read property 'beforeEach' of undefined

3.Solution

  1. router.js使用export default时,main.js使用import xxx from
  2. router.js使用export 时,main.js使用import {xxx} from

4.Ref

  1. vue-router https://router.vuejs.org/zh/g...
  2. ES6 export && export default 差异总结 https://juejin.im/post/5abe3e...

Stefango
7 声望0 粉丝

Email: c3RlZmFuZ29AcXEuY29t