import Vue from 'vue'
import Home from './Home'
import router from './router'
new Vue({
el: '#hompage',
router,
components: { Home },
template: '<Home/>',
store
})
第一步:引入vue-router
import Vue from "vue"
import vueRouter from "vue-router"
第二步:安装插件
//注意 是vueRouter插件 而不是下文中的路由对象(router)
Vue.use(vueRouter) //vueRouter.intall = fn(Vue)
//use:function(plugin){ plugin.intall(Vue) }
/*番外 install用法举例*/
import Vue from 'vue'
var Util = {}
Util.Reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^0\.([0][1-9]$))|(^0\.[1-9][0-9]?)|
Util.age = /^([1-9]|[1-7][0-9]|80)$/ //年龄
export default {
install: function (Vue) {
Vue.Util
}
}
Vue.use(Util)
第三步:创建路由对象
const router = new Router({
mode: "hash",
linkActiveClass: "active",
routes: [
{ path: "*", component: () => import(/* webpackChunkName: "errors-404" */
"#/views/error/404.vue")
},
]
})
第四步:将配置好的路由对象配置到vue实例中
new Vue({
el: document.getElementById("app"),//更为优化,避免vue内部机制查找 (vue内部机制中寻找元素时,稍稍占一点内存)
router,
data:{
eventHub:new Vue() // 事件中心
},
components: { App },
template: '<App/>'
})
下面是一个完成的例子
router.js
import Vue from "vue"
import Router from "vue-router"
import { publicRoute, protectedRoute } from "./config"
import NProgress from "nprogress"
import "nprogress/nprogress.css"
const routes = publicRoute.concat(protectedRoute)
import Cookie from 'js-cookie'
Vue.use(Router)
const router = new Router({
mode: "hash",
linkActiveClass: "active",
routes: routes
})
// router gards
router.beforeEach((to, from, next) => {
//auth route is authenticated
const jwt = Cookie.get('jwt');
console.log(to.path)
if(to.path == '/login' || to.path == '/forgotPwd' || to.path == '/loginByAdmin') {
NProgress.start()
next()
}else{
if(jwt) {
NProgress.start()
next()
}else{
next('/login')
}
}
/*NProgress.start()
next()*/
})
router.afterEach((to, from) => {
NProgress.done()
})
export default router
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
new Vue({
el: document.getElementById("app"),//更为优化,避免vue内部机制查找 (vue内部机制中寻找元素时,稍稍占一点内存)
router,
store,
data:{
eventHub:new Vue() // 事件中心
},
components: { App },
template: '<App/>'
})