scrollBehavior的使用

基于vant 使用Tabbar
页面进行切换时,保持原页面滚动条位置不变
router /index.js

import Vue from 'vue'
import Router from 'vue-router'	
Vue.use(Router)

export default new Router({
	 scrollBehavior(to, from, savedPosition) {
	    if (savedPosition && to.meta.keepAlive) {
	     return savedPosition;
	    }
	    return to.meta;
	   },
	    routes: [{
		      path: '/tab',
		      name: 'tab',
		      component: () => import('../views/3.2/tabTest.vue'),
		      meta: {
		        keepLive: true
		      },
		      children: [
		        {
		          path: '/search',
		          name: 'search',
		          component: () => import('../views/3.2/search.vue'),
		          meta: {
		            keepLive: true,
		            x:0,
		            y:0
		          }
		        },
		        {
		          path: '/home',
		          name: 'home',
		          component: () => import('../views/3.2/home.vue'),
		          meta: {
		            keepLive: true,
		            x:0,
		            y:0
		          }
		        },
		      ]
    },]
}}

tabTest.vue

<template>
  <div class="tabTest">
    这是tab
    <router-view></router-view>

    <van-tabbar v-model="active" route>
      <van-tabbar-item replace to="/home" icon="home-o">标签</van-tabbar-item>
      <van-tabbar-item replace to="/search" icon="search">标签</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
export default {
  data() {
    return {
      active: 0,
      timeId: ""
    };
  },
  mounted() {
    window.addEventListener("scroll", this.justifyPos);
    window.onscroll = this.justifyPos;
  },
  methods: {
    justifyPos() {
      if (this.timeId) clearTimeout(this.timeId);
      this.timeId = setTimeout(() => {
        this.$route.meta.y = window.pageYOffset;
      }, 300);
    }
  },
  destroyed() {
    // 当组件销毁的时候,移除滚动行为监听, 清空定时器;
    // 该方法是绑定到 window 身上,即使跳转到其他组件,仍然会监听页面的滚动行为
    console.log("页面销毁了");

    window.removeEventListener("scroll", this.justifyPos);
    clearTimeout(this.timerId);
  }
};
</script>

<style lang='less'>
</style>

search.vue 、home.vue

<template>
  <div>
    <div v-for="el in 50" :key="el">{{el}}</div>search
  </div>
</template>

<script>
export default {
  data() {
    return {};
  }
};
</script>

<style>
</style>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值