前回に引き続きVue.jsの学習記録です。
今回はVue.jsを使ってランダムなニックネームを表示する簡単なアプリケーションを作りました。
参考:https://zenn.dev/sdkfz181tiger/books/363d20b1e591fc/viewer/f853ce
全体のHTMLは以下の通り。
index.html
<html>
<head>
<meta charset="UTF-8"/>
</head>
<body>
<div id="app">
<p class="d-title">
{{ appName }}
</p>
<p class="d-line-1">
あなたのニックネームは
</p>
<p class="d-line-2">
{{ nickname }}
</p>
<p class="d-line-3">
です!!
</p>
</div>
<!-- JavaScript -->
<script src="https://unpkg.com/vue@next" defer></script>
<script src="script.js" defer></script>
</body>
</html>
次にjavascriptです。
まずVue.jsで使うデータを用意します。
script.js
const myData = {
appName: "ニックネームメーカー",
nickname: "ニックネーム",
names: [
"スライム",
"スライムベス",
"メタルスライム",
"はぐれメタル",
"メタルキング"
]
}
names配列の中からランダムな配列を返す関数を定義します。
Vue.jsにおける関数の定義はmethods:{}の形で記述します。
script.js
methods:{
roulette(){
//ランダムな0から1までの整数を生成し、names配列の数までの数と掛け合わせる
let rdm = Math.random() * this.names.length;
//生成した整数の小数点以下を切り捨てて変数indexとして定義
let index = Math.floor(rdm);
//names配列からindex番目のオブジェクトを持ってくる
this.nickname = this.names[index];
}
}
全体のコードはこんな感じになります
script.js
const myData = {//Vue.jsで使うデータを用意する
appName: "ニックネームメーカー",
nickname: "ニックネーム",
names: [
"スライム",
"スライムベス",
"メタルスライム",
"はぐれメタル",
"メタルキング"
]
}
const app = Vue.createApp({//Vue.jsを準備する
data() {
return myData;
},
created() {//サイト訪問時の処理
console.log("roulette!!");
this.roulette();
},
methods:{
roulette(){
console.log("tick!!");
let rdm = Math.random() * this.names.length;
let index = Math.floor(rdm);
this.nickname = this.names[index];
}
}
});
app.mount("#app");//Vue.jsを起動する