浏览代码

倒计时指令

Xiao_123 11 月之前
父节点
当前提交
cedf1d1afa
共有 3 个文件被更改,包括 99 次插入1 次删除
  1. 71 0
      src/directives/countDown/countTimer.vue
  2. 25 0
      src/directives/countDown/index.js
  3. 3 1
      src/directives/index.js

+ 71 - 0
src/directives/countDown/countTimer.vue

@@ -0,0 +1,71 @@
+<template>
+  <div class="countdown-timer" v-if="!isCountdownFinished">
+    <div>{{ remainingTime }}</div>
+    <div>浏览得积分 +{{ score }}</div>
+  </div>
+</template>
+
+<script>
+export default {
+  name: 'CountdownTimer',
+  props: {
+    duration: {
+      type: Number,
+      require: true
+    },
+    onEnd: {
+      type: Function,
+      require: true
+    },
+    score: {
+      type: Number,
+      default: 100
+    }
+  },
+  data() {
+    return {
+      count: 100,
+      remainingTime: this.duration,
+      isCountdownFinished: false // 倒计时是否结束
+    }
+  },
+  mounted() {
+    this.startTimer()
+  },
+  beforeUnmount() {
+    this.stopTimer()
+  },
+  methods: {
+    startTimer() {
+      this.timer = setInterval(() => {
+        if (this.remainingTime > 0) {
+          this.remainingTime--
+          // this.count = this.count - 6.67
+        } else {
+          this.stopTimer()
+          this.isCountdownFinished = true // 设置倒计时结束状态
+          this.onEnd()
+        }
+      }, 1000)
+    },
+    stopTimer() {
+      clearInterval(this.timer)
+    }
+  }
+}
+</script>
+
+<style scoped>
+.countdown-timer {
+  position: fixed;
+  right: 20px;
+  top: 30%;
+  text-align: center;
+  transform: translateY(-50%);
+  background-color: rgba(0, 0, 0, 0.5);
+  color: white;
+  padding: 10px;
+  border-radius: 5px;
+  font-size: 16px;
+}
+</style>

+ 25 - 0
src/directives/countDown/index.js

@@ -0,0 +1,25 @@
+import { createApp } from 'vue'
+import Snackbar from '@/plugins/snackbar'
+import CountTimer from './countTimer.vue'
+
+export default {
+  mounted(el, binding) {
+    const score = binding.value;
+    const timerDuration = 15
+
+    const tempElement = document.createElement('div')
+    el.parentNode.appendChild(tempElement)
+
+    const app = createApp(CountTimer, {
+      duration: timerDuration,
+      score,
+      onEnd: () => {
+        Snackbar.success('浏览完成, 获得' + score + '积分')
+        el.parentNode.removeChild(tempElement)
+        app.unmount(tempElement)
+      }
+    })
+
+    app.mount(tempElement)
+  }
+}

+ 3 - 1
src/directives/index.js

@@ -1,8 +1,10 @@
 import showScore from './showScore'
+import countDown from './countDown'
 
 // 自定义指令
 const directives = {
-  showScore
+  showScore,
+  countDown
 }
 
 export default {