在Vue中實現打字機的效果
阿新 • • 發佈:2019-02-17
export default {
data () {
return {
words:[], //字母陣列push,pop的載體
str:"By Punk", //str初始化
letters:[], //str分解後的字母陣列
order:1, //表示當前是第幾句話
}
},
watch:{ //監聽order值的變化,改變str的內容
order(old,newV){
if(this .order%4==1){
this.str="By Punk!"
}
else if(this.order%4==2){
this.str="looking for a job. "
}
else if(this.order%4==3){
this.str="a front-end programmer."
}
else{
this.str="coding the web..."
}
}
},
mounted(){ //頁面初次載入後呼叫begin()開始動畫
this.begin()
},
methods:{
//開始輸入的效果動畫
begin(){
this.letters=this.str.split("")
for(var i=0;i<this.letters.length;i++){
setTimeout(this.write(i),i*100);
}
},
//開始刪除的效果動畫
back(){
let L=this.letters.length;
for(var i=0;i<L;i++){
setTimeout(this .wipe(i),i*50);
}
},
//輸入字母
write(i){
return ()=>{
let L=this.letters.length;
this.words.push(this.letters[i]);
let that=this;
/*如果輸入完畢,在2s後開始刪除*/
if(i==L-1){
setTimeout(function(){
that.back();
},2000);
}
}
},
//擦掉(刪除)字母
wipe(i){
return ()=>{
this.words.pop(this.letters[i]);
/*如果刪除完畢,在300ms後開始輸入*/
if(this.words.length==0){
this.order++;
let that=this;
setTimeout(function(){
that.begin();
},300);
}
}
},
},
}