Code implementation:

  1. Create a text-scroll.vue file in the components of the project structure
<template>
    <div class="text-container">
        <transition class="" name="slide" mode="out-in">
            <p class="text" :key="text.id">{{text.val}}</p>
        </transition>
    </div>
</template>

<script>

export default {
  name: 'TextScroll',
  props: {
    dataList: {
      type: Array,
      default() {
        return[]; }},},data() {
    return{count: 0, // Current index intervalId: null, // timer ID playTime: 2000, // Timer interval}; }, computed: {text() {
      return{ id: this.count, val: this.dataList[this.count], }; }},created() {
    this.intervalId = setInterval(() => {// define timer this.gettext (); }, this.playTime); }, methods: {getText() { const len = this.dataList.length; // Get the array lengthif (len === 0) {
        return; // If the array is empty, return}if(this.count === len-1) {this.count = 0; // start from the first}else{ this.count++; }},},destroyed() { clearInterval(this.intervalId); // Clear timer},}; </script> <style scoped> .text-container{ font-size: 14px; color:#F56B6B;
    margin-right: 20px;
    height: 60px;
}

.text {
    text-align: right;
    margin: auto 0;
}

.slide-enter-active, .slide-leave-active {
    transition: all 1s;
}

.slide-enter{
    transform: translateY(40px);
}

.slide-leave-to {
    transform: translateY(-40px);
}
</style>
Copy the code
  1. Used in the header-bar component
<text-scroll :dataList="noticeList"></text-scroll>
Copy the code

Analysis of the

The transition label

Official documentation: cn.vuejs.org/v2/guide/tr…

Why setInterval instead of setTimeout

SetInterval is a circular execution, setTimeout is a delayed execution. What we want here is a setTimeout loop. A loop can be implemented with nested setTimeout, but each time a timer is registered, and then the timer is delayed for say two seconds after the current setTimeout completes, which is actually more than 2s.

When does setTimeout nesting solve a problem that setInterval does not when timers are time-consuming computations or DOM operations where the time is greater than the latency