本文介紹如何使用history插件管理瀏覽記錄
-
history插件的使用
history這個插件可以方便管理你的瀏覽記錄 cnpm install history --save import createHistory from 'history/createBrowserHistory'
-
三種方法
有三種使用方式 createBrowserHistory 現代瀏覽器使用 createBrowserHistory({ basename: '', // 基鏈接 forceRefresh: false, // 是否強制刷新整個頁面 keyLength: 6, // location.key的長度 getUserConfirmation: (message,callback) => callback(window.confirm(message)) // 跳轉攔截函數 }) createMemoryHistory 手機端使用 createMemoryHistory({ initialEntries: ['/'], // 初始載入路徑,和MemoryRouter中的initialEntries是一樣的 initialIndex: 0, // initialEntries初始載入索引 keyLength: 6, // location.key的長度 getUserConfirmation: null // 路由跳轉攔截函數 }) createHashHistory 老版本瀏覽器使用,暫不介紹
-
基本使用功能
const history = createHistory(); 創建歷史對象 const location = history.location; 獲取location對象 const unlisten = history.listen( (location, action) => { console.log(location,action) // location是location對象 // action是動作名稱,比如 "PUSH" } ) history.push('/a', { some: 'state' }) // 強制跳轉 unlisten() // 監聽解綁
-
history對象
屬性: 上面三種方法創建的history對象都有如下三個屬性 history.length 歷史記錄的條數 history.location 歷史記錄中的location對象 history.action 當前的歷史記錄是通過什么動作添加進來的,如 "PUSH" createMemoryHistory中提供了額外的兩個屬性 history.index 當前歷史記錄的索引 history.entries 歷史記錄 方法 listen方法 history.listen( (location,action) => { console.log(location,action); // location就是window.location的一個子集 // action可能的值,"PUSH", "REPLACE", "POP" } )
-
使用history實現跳轉
push 使用push可以將一條新的歷史記錄推送到歷史堆棧中 history.push('/a'); history.push('/a',{name: 'yejiawei'}); history.push({ pathname: '/a', state: { name: 'yejiawei' } }); replace方法和push方法使用形式一樣,replace的作用是取代當前歷史記錄 go,此方法用來前進或者倒退,history.go(-1); goBack,此方法用來回退,history.goBack(); goForward,此方法用來前進,history.goForward(); 另外使用createMemoryHistory創建的history對象,有canGo方法,和go方法類似
-
使用history實現路由跳轉警告
const unblock = history.block('Do you want to leave?'); 上面這個用法,就是添加一個跳轉提示信息,默認使用dom環境的window.confirm,所以如果使用非dom環境的createMemoryHistory就要使用getUserConfirmation方法實現 另外,除了傳遞一個字符串提示信息以外,還可以添加函數 const unblock = history.block( (location,action) => { return 'do you leave?' } ) 可以通過直接調用,unblock(); 實現方法解綁