滑動商品列表後,進入商品詳情,返回去後商品列表又重新載入數據,怎麼解決


vue-router,前端路由


需要後端支持

前端的做法是使用history介面

History?

developer.mozilla.org圖標

原理是通過hack所有鏈接的跳轉事件,使得跳轉不再卸載當前頁面而是通過ajax獲取新頁面的內容進行手動切換頁面,同時使用window.history介面進行手動切換url。

用戶在返回列表頁時會觸發window.onpopstate事件,在此事件中將之前保存下來的列表頁面重新載入,並滾動到之前保存的相對位置。

window.onpopstate = function(event) {
if ( typeof page_events === object ) {
page_events.deactivated();
}
var obj = event.state;
$( body ).html( $( obj.content ) );
$( window ).scrollTop( obj.scroll );
init();
if ( typeof page_events === object ) {
page_events.activated();
}
}
$( a.item[href], a.gotodetail[href] ).on( click, function(e) {
e.preventDefault();
var url = $( this ).attr( href ).replace( .html, .ajax_h5_mode.html );
var obj = {
scroll : $( window ).scrollTop(),
content: $( body ).html(),
inject : inject,
};
window.history.replaceState( obj, , window.location.href );
window.history.pushState( obj, , $( this ).attr( href ) );
if ( typeof page_events === object ) {
page_events.deactivated();
}
$.ajax( {
url: url,
cache: false,
dataType : html,
} ).then( function( response ) {
$( window ).scrollTop( 0 );
$( body ).html( $( response ) );
if ( typeof page_events === object ) {
page_events.activated();
}
} ).fail( function() {
console.log( 獲取頁面錯誤 );
} );
} );


把獲取的數據存起來,在Ajax之前做一個判斷,如果這個數據不為null,則不請求,有空上 demo


這個時候你就要在第一次請求的時候就要把返回的數據保存起來,然後每次進入列表前先判斷你保存的地方有沒有數據,如果沒有的話才請求,有的話就不請求。總之就是這麼一個道理。不懂再問吧


重不重新載入不是你控制的嗎


可以了解下pjax,用的就是上面 @趙詣 提到的history hack方案。

defunkt/jquery-pjax?

github.com圖標


又demo嗎


推薦閱讀:
相关文章