【问题标题】:Cycle animation or active class through Vue js loop通过Vue js循环循环动画或活动类
【发布时间】:2020-02-13 16:44:48
【问题描述】:

我已经在一个旧的 vanilla js 应用程序中创建了这个效果。我有一系列具有悬停动画的块,当没有悬停时,动画会逐块循环。

我已经在 Vue js 中重建了整个应用程序,其他一切都变得更加容易。这是应用程序的唯一部分,我正在努力以没有 dom 操作的“Vue”方式进行操作。基本上我有一个 3 秒的超时,组件获取“活动”类,然后该类切换到 v-for 中的下一个组件。

有什么建议吗?

【问题讨论】:

    标签: loops vuejs2 vue-component settimeout v-for


    【解决方案1】:

    您应该只需要使用data 中的属性来表示相关状态。每当您想直接操作 DOM 时,只需更新一些状态并将其相应地连接到模板。

    希望这个演示能满足您的需求:

    new Vue({
      el: '#app',
      
      data () {
        return {
          active: 0,
          
          items: [
            'Red',
            'Green',
            'Blue',
            'Yellow'
          ]
        }
      },
      
      mounted () {
        this.startTimer()
      },
      
      destroyed () {
        this.stopTimer()
      },
      
      methods: {
        onMouseEnter (index) {
          this.stopTimer()
          this.active = index
        },
        
        onMouseLeave () {
          this.startTimer()
        },
        
        startTimer () {
          if (this.timerId) {
            return
          }
        
          this.timerId = setInterval(() => {
            this.active = (this.active + 1) % 4
          }, 500)    
        },
        
        stopTimer () {
          clearInterval(this.timerId)
          this.timerId = null
        }
      }
    })
    ul {
      border: 1px solid #777;
      margin: 0;
      padding: 0;
    }
    
    li {
      list-style: none;
      padding: 5px;
    }
    
    .active {
      background: #ccf;
    }
    <script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
    
    <div id="app">
      <ul>
        <li
          v-for="(item, index) in items"
          :key="item"
          :class="{ active: active === index }"
          @mouseenter="onMouseEnter(index)"
          @mouseleave="onMouseLeave"
        >
          {{ item }}
        </li>
      </ul>
    </div>

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 2017-12-29
      • 1970-01-01
      • 2019-07-06
      • 2013-07-03
      相关资源
      最近更新 更多