分頁功能代碼實現
<div>
<a class="btn" href="#" style="..." @Click.prevent="prePage"><</a>
<a class="btn" href="#" style="..." @Click.prevent="nextPage">$gt;</a>
</div>
<script type="text/javascript">
var vm = new Vue({
el: "#searchApp",
data: {
searchData: {
key: "",
page: 1
},
total: 1,
totalPage: 1
},
created() {
// 發送請求之前給searchData賦值
const key = http.getUrlParam("key")
if (!key) {
alert("請添加搜索條件")
}
this.searchData.key = key
const page = http.getUrlParam("page") || 1
this.searchData.page = page
this.loadItemData()
},
watch: {
// 監聽searchData.page屬性
"searchData.page": {
handler(){
this.loadItemData()
}
}
},
methods: {
// 發送請求
loadItemData() {
...
},
// 上一頁
prePage(){
if (this.searchData.page > 1){
this.searchData.page--
}
},
// 下一頁
nextPage(){
if (this.searchData.page <= this.totalPage){
this.searchData.page++
}
}
}
});
</script>
刷新問題
上面的方法按照正常的get傳參方式看似正常
此時的地址欄狀態如下,點擊上一頁或下一頁時,頁面會一直刷新導致瀏覽器崩潰
http://localhost/?key=XXX&page=XXX
watch監聽到page有變化之后刷新頁面導致page重新賦值,進入死循環
const page = http.getUrlParam("page") || 1
刷新問題解決
created(){
const key = http.getUrlParam("key")
if(!key){
alert("請求添加搜索條件!!!")
}
//獲取到location中的hash,0位為"#",不保留
const hashStr = location.hash.substring(1)
//將字符串格式的hash轉成json格式[包含了key之外所有的參數]
const hashJson = http.parse(hashStr)
//將key加入到hashJson中
hashJson.key = key;
//判斷page值,沒有就賦值為1
hashJson.page = hashJson.page || 1
//將包含所有參數的json格式的hash賦值給當前searchData
this.searchData = hashJson;
//向服務區發送分頁查詢請求
this.loadItemData()
},
watch: {
"searchData.page": {
handler(){
//location的hash改變是不會再次發送請求的
//所以我們最終采取的方案是,將除了key之外的所有請求參數都放到hash中去。
//具體操作如下:
//將searchData中的數據把key去掉
const {key, ...searchDataWithOutKey} = this.searchData
//將json格式的searchDataWithOutKey轉成字符串賦值給hash
location.hash = http.stringify(searchDataWithOutKey)
//向服務區發送分頁查詢請求
this.loadItemData()
}
}
}