初めに
ここ最近Vue.jsの勉強をしているが、今日はまとまった時間が取れないのでドキュメントが読めない。そこでアニメーションを作って楽しむことにした。
どんなアプリか
映画でよくあるパスワードを破るシーン
文字がA, B, C, ... と勢いよく次々に表示され、パスワード解除!みたいなシーンを再現してみる。
実装
v-on
ディレクティブでSTARTボタンを押したら文字がA, B, C, ... と次々に表示されるようにする。
念のためSTOPボタンも用意。
<div id="app">
<button v-on:click="rotateStart()">START</button>
<button v-on:click="rotateStop()">STOP</button>
<p>{{ character }}</p>
<p>{{ message }}</p>
</div>
アルファベットはリストにしてぐるぐる回るように。
sleep で0.05秒で文字が切り替わるよう設定。
var app = new Vue({
el: '#app',
data: {
character: '',
message: '',
isTrue: true,
cipher: 'HELLO WORLD'
},
methods: {
rotateStart: async function() {
var aplhabetList = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
var cipherList = this.cipher.split('');
var count = 0;
var cipherIndex = 0;
while (this.isTrue) {
this.character = aplhabetList[count % 26];
if (cipherList[cipherIndex] === this.character) {
this.message += this.character;
if (cipherList.length === cipherIndex + 1) {
this.character = 'You broke the code!!'
break;
} else {
cipherIndex++;
}
} else if (cipherList[cipherIndex] === ' ') {
this.message += ' ';
cipherIndex++;
}
await this.sleep(50);
count++;
}
},
rotateStop: function(){
this.isTrue = false
this.message = ''
},
sleep: time => new Promise(resolve => setTimeout(resolve, time))
}
})
- 画面更新後
- START押下後
動いてる!楽しい!
- 自然停止