LoginSignup
0
0

More than 3 years have passed since last update.

【Vue.js】Vue.jsを使って「おみくじアプリ」を作ってみた

Posted at

概要

Vue.jsを使って「おみくじアプリ」を作ってみました。
アプリの挙動は以下の通りです!

Omikuji App.gif

アプリの機能

「あなたの今日の運勢」ボタンを押下すると
大吉、中吉、小吉、末吉、凶のうちのどれかがランダムで表示されます。

そして運勢結果に合わせていらすとやでゲットした画像も表示されます。

コードの説明

ランダムにおみくじ結果を表示する処理には乱数生成を利用します。

Math.random()の値は0から1までの間をとるため、
その値に配列の長さをかけて小数点以下を切り捨てることにより、
今回の配列の全要素番号である0から4の値をランダムに出力します。

script.js
new Vue({
    el: '#app',
    data(){
        return {
          list: ["大吉","中吉","小吉","末吉",""],
          result: null
        }
    },
    methods: {
      start: function(){
        const rnd = Math.floor(Math.random() * this.list.length);
        this.result = this.list[rnd];
      }
    }
});

上記の処理で詰めたresultの値をHTML側で表示させます。

index.html
<p class="omikuji-result" v-if="result">{{result}}です!</p>

また今回作成したアプリのように結果に合わせて画像を表示させる場合は、
以下のように画像を配置してあげてください。

ディレクトリ構成
├── index.html
├── script.js
├── img
     ├── 大吉.png
     └── 中吉.png
     └── 小吉.png
     └── 末吉.png
     └── 凶.png

コード全量

こちらHTML,JSのコードの全量です。

index.html
<head>
    <meta charset="UTF-8" />
    <title>おみくじアプリ</title>
</head>
<body>
  <div id="app">
    <div class="text-area">
      <button class="omikuji-button" @click="start">あなたの今日の運勢</button>
      <p class="omikuji-result" v-if="result">{{result}}です!</p>
      <p v-if="result == '大吉'"><img src="img/大吉.png" class="image"></p>
      <p v-else-if="result == '中吉'"><img src="img/中吉.png" class="image"></p>
      <p v-else-if="result == '小吉'"><img src="img/小吉.png" class="image"></p>
      <p v-else-if="result == '末吉'"><img src="img/末吉.png" class="image"></p>
      <p v-else-if="result == '凶'"><img src="img/凶.png" class="image"></p>
    </div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="script.js"></script>
</body>
<style scoped>
.omikuji-button {
  font-size: 20px;
  padding: 12px 20px;
  border: none;
  -webkit-appearance: none;
  background:#FF66FF;
  color: #eee;
  border-radius: 4px;
}
.omikuji-result {
  color: #444444;
  font-size: 35px;
  font-weight:700; 
}
.text-area {
  text-align: center;
}
.image {
  width: 15%;
    height: auto;
}
</style>
script.js
new Vue({
    el: '#app',
    data(){
        return {
          list: ["大吉","中吉","小吉","末吉",""],
          result: null
        }
    },
    methods: {
      start: function(){
        const rnd = Math.floor(Math.random() * this.list.length);
        this.result = this.list[rnd];
      }
    }
});

参考

記事「Vue.jsでおみくじアプリを作ってみた」

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0