<template>
  <!-- 回到顶部 -->
  <div
    v-show="showGoTopButton"
    class="page-component-up"
    @click="goTop"
    :style="borderStyle"
  >
    <i class="el-icon-caret-top" :style="iconStyle"></i>
  </div>
</template>

<script>
export default {
  name: 'GoTop',
  data () {
    return {
      showGoTopButton: false
    }
  },
  computed: {
    // 返回顶部按钮背景颜色
    borderStyle () {
      return {
        boxShadow: `0 0 6px ${this.$store.state.framework.theme}`
      }
    },
    iconStyle () {
      return {
        color: this.$store.state.framework.theme
      }
    }
  },
  mounted () {
    // 为content添加滚动监听，显示返回顶部按钮
    this.content = document.querySelector('#content')
    this.content && this.content.addEventListener('scroll', this.scrollFunc)
  },
  destroyed () {
    // 为content清除滚动监听
    this.content && this.content.removeEventListener('scroll', this.scrollFunc)
  },
  methods: {
    // 返回顶部
    goTop () {
      this.showGoTopButton = false
      this.content.scrollTop = 0
    },
    scrollFunc () {
      const contentScrollTop = this.content.scrollTop
      if (contentScrollTop > 600) {
        this.showGoTopButton = true
      }
      if (contentScrollTop < 500) {
        this.showGoTopButton = false
      }
    }
  }
}
</script>

<style>
  .page-component-up {
    position: fixed;
    z-index: 99;
    right: 100px;
    bottom: 100px;

    width: 40px;
    height: 40px;

    cursor: pointer;
    transition: 0.3s;

    border-radius: 20px;
    background-color: #fff;
    box-shadow: 0 0 6px #4992fc;
  }

  .page-component-up i {
    display: block;

    text-align: center;

    color: #4992fc;

    font-size: 18px;
    line-height: 40px;
  }
</style>
