vue-router常見用法

hash模式和history模式

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

  1. 修改頁面的標題
router.beforeEach((to, from, next) => {
    window.document.title = to.meta.title;
    next();
})
複製代碼

微信中給vue單頁應用設置標題

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;
複製代碼
  1. 每次頁面跳轉控制滾動到最頂部
router.afterEach((to, from, next) => {
    window.scrollTo(0, 0);
})
複製代碼
  1. 判斷是否登陸
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')
複製代碼

命名chunk及把組件按組分塊

命名chunk

使用了異步路由以後, 編譯出來的每一個頁面的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規則是根據註釋來判斷的;

匹配404路由

在路由列表的最下面加上以下代碼

new Router({
  routes: [{
        // 此處省略N個路由
        {
          name: '404',
          path: '/404',
          component: () => import('./notFound.vue')
        },
        {
            path: '*', // 此處需特別注意至於最底部
            redirect: '/404'
        }
  }]
})
複製代碼
相關文章
相關標籤/搜索