自定義一個回到頂部Vue指令

CSS樣式:

<style>
     * {
       margin: 0;
       padding: 0;
     }
     html, body, #app {
       height: 100%;
     }
     #app {
       display: flex;
       flex-direction: column;
       overflow: hidden;
     }
     section {
       flex: 1;
       overflow-y: auto;
     }
     li {
       height: 28px;
       line-height: 28px;
       border-bottom: 1px solid #000000;
     }
     header, footer {
       height: 40px;
       background: red;
     }
     .gotop {
       width: 50px;
       height: 50px;
       position: fixed;
       bottom: 20px;
       right: 20px;
       border: 1px solid blue;;
       border-radius: 50%;
     }
</style>
<body>
    <div id="app">
      <header></header>
      <section v-gotop>
        <ul>
          <li v-for="item in 200" :key="item">{{ item }}</li>
        </ul>
        <!-- <div class="gotop" @click="goTop">goTop</div> -->
      </section>
      <footer></footer>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    <script>
      // goTop 組件的配置對象
      const goTop = {
        data () {
          return {
            visible: false
          }
        },
        template: `
          <div v-show="visible" class="gotop" @click="goTop">點我</div>
        `,
        methods: {
        //點擊回到頂部函數
          goTop () {
            this.$el.parentElement.scrollTop = 0
          }
        }
      }
      
        // 註冊一個全局自定義指令 `v-gotop`
      Vue.directive('gotop', (el, binding) => {
        // 1. 使用 Vue.extend() 方法來擴展 Vue , 得到一個 Vue 子類
        const GoTop = Vue.extend(goTop)
        // 2. new GoTop 生成 GoTop 的實例
        const instance = new GoTop()
        // 3. instance.$mount() 進行掛載。但是不要提供掛載點。
        //    這個 instance 就有了 $el 屬性
        instance.$mount()
        // 4. 就將這個 DOM 對象插入到 el 中
        el.appendChild(instance.$el)
        // 5. 當前元素的滾動條大於可視高度時,出現回到頂部的按鈕
        el.addEventListener('scroll', () => {
          if (el.scrollTop >= el.clientHeight) {
            instance.visible = true
          } else {
            instance.visible = false
          }
        })
      })
      const vm = new Vue({
        el: '#app'
      })
    </script>
  </body>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章