vue自定义回到顶部功能(刚开始使用了element中的回到顶部组件,但跟我项目设置的切换页面回到顶部功能冲突了,用了这种方式)

App.vue页面

<template>
  <div id="app" class="app">
    <component :is="layout">
      <router-view v-if="isRouterAlive"/>
    </component>
    <!--      回到顶部-->
    <div v-show="iftop" class="totop flexCenter"  @click="backTop">
      <i class="el-icon-caret-top" style="color: #CC1720"></i>
    </div>


<!--    登录弹框-->
     <login></login>

  </div>
</template>

<script>
  import * as auth from '@/utils/auth'
  import login from './components/login'
  export default {
    name: 'App',
    provide(){
      return {
        reload: this.reload,
      }
    },
    components:{
      login
    },
    data(){
      return {
        default_layout: 'default',//设置layout
        isRouterAlive: true,
        iftop: false
      }
    },

    computed:{
      layout(){
        return (this.$route.meta.layout || this.default_layout) + '-layout'
      },
    },


    //解决isLogin needLogin变量页面刷新后被重置的问题
    created() {
      let userInfo = auth.getAdminInfo();
      if(userInfo){
        this.$store.commit('user/setUserLogin')
      }else{
        this.$store.commit('user/logOut')
      }
    },
    mounted() { //监听scroll方法
      window.addEventListener('scroll', this.handleScroll)
    },
    beforeDestroy() { //及时释放
      window.removeEventListener('scroll', this.handleScroll)
    },

    methods: {
      //通过声明reload方法,控制router-view的显示或隐藏,从而控制页面的再次加载
      reload(){
        this.isRouterAlive = false;
        this.$nextTick(function () {
          this.isRouterAlive = true;
        })
      },


      handleScroll() {
        let iftop = window.pageYOffset > 400 ? true : false
        this.iftop = iftop
      },
      backTop() {
        window.scrollTo({top:0,behavior: 'smooth',})
      }

    }
  }
</script>

<style lang="scss">
  .app {
    position: relative;
  }
  .totop {
    position: fixed;
    bottom: 100px;
    right: 40px;
    width: 40px;
    height: 40px;
    background-color: #fff;
    border-radius: 50%;
    box-shadow: 0 0 6px rgba(0,0,0,.12);
    cursor: pointer;
    z-index: 5;
  }

  html,body {
    height: 100%;
  }
  /*.app {*/
  /*  height: 100vh;*/
  /*  overflow-x: hidden;*/
  /*}*/

/*body {*/
/*  overflow-x: hidden;*/
/*}*/

/*body::-webkit-scrollbar {*/
/*   0px;*/
/*  height: 0px;*/
/*}*/
body .-o-scrollbar {
  -moz-appearance: none !important;
  background: rgba(0, 255, 0, 0) !important;
}
body {
  -ms-scroll-chaining: chained;
  -ms-overflow-style: none;
  -ms-content-zooming: zoom;
  -ms-scroll-rails: none;
  -ms-content-zoom-limit-min: 100%;
  -ms-content-zoom-limit-max: 500%;
  -ms-scroll-snap-type: proximity;
  -ms-scroll-snap-points-x: snapList(100%, 200%, 300%, 400%, 500%);
  -ms-overflow-style: none;
  overflow: auto;
}

// img[lazy=error]{
//   width:60px!important;height:60px!important;
// }
// img[lazy=loaded]{
//   width:60px!important;height:60px!important;
// }

</style>
原文地址:https://www.cnblogs.com/duanzhenzhen/p/14240010.html