Vue.js

Vue.jsを試してみているのでそのメモです。

とりあえず今回は"Hello Vue.js"とVue.jsを使って出力させてみます。

 

 

準備(ファイル作成)

以下のような構成でファイルを作成します。

vue_sample

  |--index.html

  |--index.js

  |--styles.css

 

 

HTMLファイルにVue.jsを読み込む設定を記述

以下のVue.js公式ページのCDNの項目にあるurlをコピーして、htmlファイルのbodyの下に貼り付けます。

jp.vuejs.org

 

その後、同じ階層に存在するjsファイルを読み込む記述をVue.jsの読み込みより下に書きます。

 

 

index.html

<!DOCTYPE html> 

<html>

<head>

    <meta charset="utf-8" />

    <title>vue_sample</title>

    <link rel="stylesheet" href="styles.css">

</head>

<body>

 

    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>

    <script src="index.js"></script>

</body>

</html> 

 

 

Vueインスタンスの作成とHTMLファイルで表示させたい部分の設定

vueインスタンスのelで指定したidを持ったdivタグをhtmlファイルに記載します。

この中が、vueの使える部分になります。

 

index.js

var app = new Vue({
    el: '#app',
})

 

 

index.html

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

    <title>vue_sample</title>

    <link rel="stylesheet" href="styles.css">  

</head>

<body>


    <div id="app">

    </div>

 

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>

<script src="index.js"></script>

</body>

</html>

 

 

 

文字を出力させる

vueインスタンスのdata属性に指定した値をhtmlに出力させるには、{{  }} の中にその属性名を指定してあげます。

 

index.js

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue.js'
    }
})

 

index.html

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

     <title>vue_sample</title>

     <link rel="stylesheet" href="styles.css">

</head>

<body>


    <div id="app">
        <p>{{message}}</p> 

    </div>

 

    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>

    <script src="index.js"></script>

</body>

</html>

 

ブラウザにはきちんとHello Vue.jsと出力されます。

 

gyazo.com

 

 

 

これはただテンプレートを描画しているだけに見えますが、その裏側では多くの処理が行われています。

dataとdomが関連づけられ、全てがリアクティブになっています。

jsのコンソールを開いてapp.messageの値を変えると、ブラウザに表示される値も変わります。

gyazo.com