1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
7. <title>跑马灯效果</title>
8. </head>
9. <body>
10. <!-- 开发环境版本,包含了有帮助的命令行警告 -->
11. <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
12. <div id="app">
13. <input type="button" value="跑起来" @click="run">
14. <input type="button" value="歇一会" @click="stop">
15. <h3>{{msg}}</h3>
16. </div>
17.
18. <script>
19. var app = new Vue({
20. el: '#app',
21. data: {
22. msg:"大家好,我是测试小白!",
23. intervalId:null
24.
25. },
26. methods: {
27. // 跑起来
28. // this.msg.substring(0,1) substring(起始索引,结束索引[不包含,不写默认取到结尾])
29. //setInterval()=> this指向外部
30. run(){
31. if(this.intervalId!==null)return // 定时器id不为null时直接返回,不会再次创建新的定时器
32.
33. this.intervalId = setInterval(()=>{
34. var header = this.msg.substring(0,1);
35. var body = this.msg.substring(1);
36. this.msg = body + header;
37.
38. },200)
39.
40.
41. },
42. // 停止
43. stop(){
44. clearInterval(this.intervalId) // 清除定时器
45.
46. this.intervalId=null // 清除定时器时,id置为空 不影响下次重新创建
47. }
48.
49. }
50.
51. })
52. </script>
53. </body>
54. </html>