Vue.js開発入門 > Chapter 1 Vue.jsって何?

04 試してみよう

Vue.jsでプログラムを作ってみます。
ボタンをクリックしたら、クリックした回数をカウントしてみます。

  • countup.html
      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
    
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>Vue.js sample</title>
            <link rel="stylesheet" href="style.css" >
            <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
        </head>
        
        <body>
            <h2>クリックしたらカウントアップ</h2>
            <div id="app">
                <p> {{count}}回</p>
                <button v-on:click="countUp">カウント</button>
            </div>
            
            <script>
            new Vue({
                el: "#app",
                data: {
                    count:0
                },
                methods: {
                    countUp: function() {
                        this.count++;
                    }
                }
            })
            </script>
            
        </body>
    </html>

たったこれだけの記述でカウントアップするボタンを設置することができました。
Vue.jsの記述はシンプルですね!

  • countup1.html
      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
    
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>Vue.js sample</title>
            <link rel="stylesheet" href="style.css" >
            <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
     
            <script>
            window.onload = function() {
                new Vue({
                    el: "#app",
                    data: {
                        count:0
                    },
                    methods: {
                        countUp: function() {
                            this.count++;
                        }
                    }
                })
            }
            </script>
        </head>
        
        <body>
            <h2>クリックしたらカウントアップ</h2>
            <div id="app">
                <p> {{count}}回</p>
                <button v-on:click="countUp">カウント</button>
            </div>
        </body>
    </html>

別の書き方の例です。
「<script>」を「<head>」の中に置いています。
「window.onload」というJavaScriptのイベントハンドラーを使えば、こういう書き方ができるんですね。

(参考)JavaScript_EventHandlers_window.onload



これでボタンをクリックしたら回数がカウントアップされるWebページをVue.jsで作ることができました。


トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2019-08-10 (土) 08:14:08 (1714d)