300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > vue tab页面缓存处理

vue tab页面缓存处理

时间:2019-03-03 16:19:46

相关推荐

vue tab页面缓存处理

vue tab页面缓存处理

问题:使用vant 框架。底部导航切换,tab页面缓存

解决:

1.index 页面 xml 设置

<keep-alive><router-view v-if="$route.meta.keepAlive" style="margin-bottom: 50px"/></keep-alive><router-view v-if="!$route.meta.keepAlive" style=" margin-bottom: 50px"/>

注意:style=" margin-bottom: 50px" 设置是为了底部数据不被导航按钮遮住,导航栏默认有高度

2.路由中设置 route.js

{path: '/',component: () => import('@/views/index'),redirect: '/home',meta: {title: '首页',keepAlive: true},children: [{path: '/home',name: 'Home',component: () => import('@/views/home/index'),meta: {title: '首页', keepAlive: true}},{path: '/mine',name: 'Mine',component: () => import('@/views/mine/index'),meta: {title: '个人中心', keepAlive: true}}]},

注意:keepAlive: true 代表页面需要缓存,切换页面只走一次 create()函数

3.其他问题

问题:如果首页是列表,切换tab 或者从列表进去详情,回到列表页 ,列表不会记录之前滑动的位置

解决:记录列表滑动的位置,离开页面后 保存到缓存,重新返回列表时,取出缓存的位置,设置列表指定到该位置。

核心代码如下:

a.首页

<!-- --><template><div><div v-for="(item,index) in lists" :key="index"><div style="height: 50px;color: #449908;margin: 10px;background-color: #991908;text-align: center;line-height:50px" @click="toDetail(item)">{{item }}</div></div></div></template><script>export default {name: 'Home',data() {return {lists: [],scrollValue:''};},methods: {toDetail(item){this.scrollValue = window.scrollYconsole.log("详情页")this.$router.push({path: '/detail', query: {item: item,position: this.scrollValue}})}},//离开当前路由beforeRouteLeave(to, from, next) {if (from.meta.keepAlive) {console.log("首页滑动的位置" + window.scrollY)this.scrollValue = window.scrollYlocalStorage.setItem('position', this.scrollValue)}next();},activated() {let position = localStorage.getItem('position')this.$nextTick(() => {//必须使用nextTick(在下次 DOM 更新循环结束之后执行延迟回调)if (position!==undefined){window.scroll(0, position)}})},created() {for (let i = 0; i < 50; i++) {this.lists.push('测试' + (i + 1))}console.log("Home===>created()")}}</script><style scoped></style>

b.详情页:

<!-- --><template><div class=''>详情:{{value }}滑动距离顶部位置:{{scrollHeight }}</div></template><script>export default {data() {return {value: '',scrollHeight: ''};},methods: {},created() {const item = this.$route.query.item;const position = this.$route.query.position;this.value = itemthis.scrollHeight = positionconsole.log("列表页面传过来的值1:", item)console.log("列表页面传过来的值2:", position)},destroyed() {console.log("详情页面生命周期destroyed:")localStorage.setItem('position', this.scrollHeight)}}</script><style scoped></style>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。