初学VUE 走马灯效果

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="./js/vue.js"></script>
</head>

<body>
  <div id="a">
    <input type="button" value="浪起来" @click='lang'>
    <input type="button" value="稳住" @click='tingzhi'>
    <p>{{ msg }}</p>
  </div>
</body>
<script>
  // vm上的数据发生变化 就会把新的数据从data中同步到页面中去
  const vm = new Vue({
    el: '#a',
    data: {
      msg: '大家一起嗨起来~~~!',
      id: null,
    },
    methods: {
      lang() {
        //   vue中想要获取上个局部数据 要用到this 但是这里有用到了定时器 this会指向window 所以我用了es6中的 =>函数
        if (this.id != null) return;
        // 要给一个点击的判断 要不然就会出现多次运行定时器 停止就不会管用了
        this.id = setInterval(() => {
          const q = this.msg.substring(0, 1);
          const h = this.msg.substring(1);
          // 把截取的字符创拼接到 msg 中
          this.msg = h + q;

        }, 100)
      },
      tingzhi() {
        clearInterval(this.id);
        // 要把初始值在赋给 msg 要不然定时器不会再执行
        this.id = null;
      }
    }
  })
</script>

</html>

很简单的走马灯效果

 关注公众号 WEB前端大澳 领取资料

猜你喜欢

转载自www.cnblogs.com/lwa1999/p/11741535.html