Vue — v-load封裝 loading效果

萬事順意發表於2024-03-11
<template>
  <div class="app">
    <div class="box" v-load="isLoading">
      <ul>
        <li v-for="(item, index) in list" :key="index">
          {{ item.name }}
        </li>
      </ul>

    </div>

  </div>

</template>

<script>


export default {

  data() {
    return {
      list: [],
      isLoading: true
    }
  },
  created() {
    setTimeout(() => {
      this.list = [
        { name: '1111' },
        { name: '2222' },
        { name: '3333' },
        { name: '4444' }

      ]
      this.isLoading = false
    }, 3000)
  },
  methods: {

  },
  directives: {
    // 透過新增或者移除類名 實現新增移除Load效果
    load: {
      //在這個鉤子函式中 設定預設狀態
      inserted(el, binding) {
        binding.value ? el.classList.add('load') : el.classList.remove('load')
      },
      //這個函式用來更新類名狀態
      update(el, binding) {
        binding.value ? el.classList.add('load') : el.classList.remove('load')
      }
    }
  }
}
</script>

<style>
.box {
  width: 500px;
  height: 500px;
  background-color: #f7d6d6;
  position: relative;
}

/* 1.準備一個類名,封裝指令v-load 實現請求loading效果*/
.load::before {
  content: '';
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background: #000 url('./assets/image/load.gif') no-repeat center;
}
</style>

相關文章