hash模式(vue-router默认hash模式)就是看到路由上面会有一个 #
号, 例如http://localhost:8800/#/
; javascript经过hashChange事件来监听url的变化 history模式,就是直接匹配的/
, 这种模式充分利用 history.pushState
API来完成URL跳转而无需从新加载页面javascript
const router = new VueRouter({ // 使用HTML5的History路由模式 mode: 'history', routes: [...] }) 复制代码
history模式, 须要后端配置支持, 由于咱们的应用是单页应用, 后端若是没有配置, 访问 http://localhost:8800/home
就是404; 后端须要配置在接收到全部的请求后, 都会指向同一个index.htmlcss
beforeEach和afterEachhtml
router.beforeEach((to, from, next) => { window.document.title = to.meta.title; next(); }) 复制代码
function addELementToBody(el) { if (document.body) { document.body.appendChild(el); } else { window.onload = function () { document.body.appendChild(el); }; } } function setTitle(title = '') { if (title) { window.document.title = title; // 兼容IOS下的微信 if (/ip(hone|od|ad)/i.test(navigator.userAgent)) { const i = document.createElement('iframe'); i.src = '/favicon.ico'; i.style.display = 'none'; i.onload = function () { setTimeout(() => { i.remove(); }, 9); }; addELementToBody(i); } return Promise.resolve(); } return Promise.reject('请传递title参数'); }; export default setTitle; 复制代码
router.afterEach((to, from, next) => { window.scrollTo(0, 0); }) 复制代码
router.beforeEach((to, from, next) => { if(window.localStorage.getItem('token')) { next(); } else { next('/login'); } }) 复制代码
next参数为false时, 能够取消导航, 设置为具体的路径能够导航到指定的页面;vue
正确的使用好导航钩子能够实现一些全局性的功能, 并且便于维护java
若是使用babel, 则须要添加 syntax-dynamic-import
该插件webpack
懒加载的写法:web
const Foo = () => import('./Foo.vue') 复制代码
使用了异步路由以后, 编译出来的每一个页面的js都叫作chunk(块),默认的chunk都是以0, 1, 2, 3 ... 来命名的, 这样开发的时候不太方便看出具体是哪一个模块的chunk, 咱们能够给每一个chunk都进行命名; 在webapck配置的出口output里经过设置chunkFilename字段修改chunk命名:vue-router
{ output: { publicPath: '/dist/', // [hash:8] 修改成8位数的hash值 filename: '[name].[hash:8].js', chunkFilename: '[name].[hash:8].chunk.js' }, } 复制代码
有了chunk后, 在每一个页面(.vue文件)里写的样式也须要配置后才会打包进main.css, 不然仍然会经过JavaScript动态建立<style>
标签的形式写入. 配置插件后端
plugins: [ new ExtractTextPlugin({ filename: '[name].[hash:8].css', allChunks: true }), ] 复制代码
使用命名chunk, 一个特殊的注释语法来提供chunk name微信
const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue') const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue') const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue') 复制代码
命名相同的webapck会打包到同一个chunk下;
.babelrc的配置
{ "presets": ["stage-3", "env"], "plugins": ["transform-runtime", "syntax-dynamic-import"], // "comments": false, "env": { "production": { "plugins": [ ["transform-remove-console"] ] } } } 复制代码
"comments": false, 该项必定不要保留,由于会把注释的部分去掉, 可是命名chunk规则是根据注释来判断的;
在路由列表的最下面加上以下代码
new Router({ routes: [{ // 此处省略N个路由 { name: '404', path: '/404', component: () => import('./notFound.vue') }, { path: '*', // 此处需特别注意至于最底部 redirect: '/404' } }] }) 复制代码