<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>利用session存值</title>
<style>
* {
padding: 0;
margin: 0;
}
ul {
padding: 0 6px;
}
li {
list-style: none;
width: 100%;
height: 40px;
line-height: 40px;
text-align: center;
/*border: 1px dashed red;*/
margin-top: 9px;
box-sizing: border-box;
}
li:nth-child(odd) {
border: 1px dashed red;
}
li:nth-child(even) {
border: 1px dashed blue;
}
button {
width: 90%;
height: 40px;
margin-left: 5%;
border: 2px solid red;
margin-top: 9px;
}
[v-cloak] {
display: none;
}
</style>
</head>
<body>
<div id="app">
<button @click="btn" type="button">点击加载更多</button>
<ul v-for='item in msgNum' v-cloak>
<li v-for='items in item.value'>{{ items.id }}</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var vm = new Vue({
el: '#app',
data: {
msgNum: [],
page: 5
},
methods: {
// 4. 点击更改参数 并继续调用
btn() {
this.page++
this.axiosData()
},
//3.进行页面的数据请求
async axiosData() {
const {data} = await axios.post('https://bj.qhtest.site/byzz/v1.home/analysis', {
page: this.page
})
if(data.code == 200) {
//3.1 请求成功之后 赋值 并且存入到session中 (当页面再次刷新时就有了session)
this.msgNum = this.msgNum.concat(data.data.list)
sessionStorage.setItem('datas', JSON.stringify(this.msgNum))
}
},
//2. 页面一加载就判断session是否存在
sessionData() {
// 2.1 如果存在
if(sessionStorage.getItem('datas')) {
// 2.2 就把获取到的session值赋值到自定义并可执行的数组中
this.msgNum = JSON.parse(sessionStorage.getItem('datas'))
// 2.3 如果页面加载后没有session
} else {
// 2.4 就让当前的this.msgNum 从新赋值 并执行数据请求
this.msgNum = this.msgNum
this.axiosData()
};
}
},
//1. 首先执行 进行判断
created() {
this.sessionData()
}
})
</script>
</body>