Vue入門07練習--走馬燈文字
阿新 • • 發佈:2018-10-31
函式問題,箭頭函式
程式碼:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="js/vue.js" ></script> </head> <body> <div id="app"> <button @click="move">走</button> <button @click="stop">停</button> <h3>{{msg}}</h3> </div> <script> new Vue({ el:"#app", data:{ msg:"hello Vue", timer:null }, methods:{ move:function(){ //防止重複點選,出現抽風現象 if(this.timer){ return } //es5中函式巢狀函式,會形成閉包,導致this指向問題 // var _this = this 定義_this快取this // this.timer = setInterval(function(){ // var start = _this.msg.substring(0,1) // var end = _this.msg.substring(1) // _this.msg = end+start // },400) //es6中可以用箭頭函式,this指向是根據上下文 this.timer = setInterval(()=>{ var start = this.msg.substring(0,1) var end = this.msg.substring(1) this.msg = end+start },400) }, stop:function(){ clearInterval(this.timer) this.timer = null } } }) </script> </body> </html>
顯示: