本文实例为大家分享了Vue3实现跑马灯效果的具体代码,供大家参考,具体内容如下

先看效果:

html部分代码

<div class="app">              <p :class="{tabcolor:color}">{{str}}</p>              <button @click="play">开始</button>              <button @click="stop">停止</button>  </div>

注意: :class="{tabcolor:color}" 是给<p></p>标签内的文字加上一个颜色,当我们点击开始按钮的时候。 

CSS部分代码

.tabcolor {                  color: cornflowerblue;              }

CSS部分的代码很简单,就是给了一个添加颜色的类。

Vue部分代码

Vue.createApp({              data() {                  return {                      str: "你好啊,我是稳重聪头~",                      id: null,                      color: false,                  }              },              methods: {                  play() {                      clearInterval(this.id);                      this.color = !this.color;                      this.id = setInterval(() => {                          this.str = this.str.slice(1) + this.str.slice(0, 1)                      }, 800)                  },                  stop() {                      clearInterval(this.id);                      this.color = false;                  }              }          }).mount(".app")

分析:

1、data上定义一个字符串,这个字符串就是要在<p></p>标签里进行滚动的。
2、给开始和关闭按钮,绑定事件:v-on; @cliick就是v-on的简写。
3、在按钮的事件函数中,写相关的业务逻辑代码:拿到str字符串,然后 调用字符串 slice 来进行字符串的截取操作,把第一个字符截取出来,放到最后一个位置即可。
4、为了实现最终结果,自动截取的功能,需要把步骤三的代码放到一个定时器中去。

最后在送上完整代码 

<!DOCTYPE html>  <html lang="en">         <head>          <meta charset="UTF-8">          <meta http-equiv="X-UA-Compatible" content="IE=edge">          <meta name="viewport" content="width=device-width, initial-scale=1.0">          <title>Document</title>          <script src="./js/vue.js"></script>          <style type="text/css">              .tabcolor {                  color: cornflowerblue;              }          </style>      </head>         <body>          <div class="app">              <p :class="{tabcolor:color}">{{str}}</p>              <button @click="play">开始</button>              <button @click="stop">停止</button>          </div>      </body>      <script>          Vue.createApp({              data() {                  return {                      str: "你好啊,我是稳重聪头~",                      id: null,                      color: false,                  }              },              methods: {                  play() {                      clearInterval(this.id);                      this.color = !this.color;                      this.id = setInterval(() => {                          this.str = this.str.slice(1) + this.str.slice(0, 1)                      }, 800)                  },                  stop() {                      clearInterval(this.id);                      this.color = false;                  }              }          }).mount(".app")      </script>  </html>