LoginSignup
0
0

More than 3 years have passed since last update.

Vue.js 宣言的レンダリング

Last updated at Posted at 2020-09-01

HTMLでvueを使えるようにする

hmtlでvueを読み込ませませます。

<!-- 開発バージョン、便利なコンソールの警告が含まれています -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<!-- 本番バージョン、サイズと速度のために最適化されています -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

以下のサンプルコードのようにscriptタグの最上位にコードを追記します。

宣言的レンダリングを試してみる

サンプルコード

index.html
<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product App</title>
</head>

<body>
    <div id="app">
        <h1>{{ product }}</h1>
    </div>
    // プロジェクトにvueを読み込ませる
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="main.js"></script>
</body>

</html>
main.js
var app = new Vue({
    el: '#app',
    data: {
        product: 'Socks'
    }
})

表示例

スクリーンショット 2020-09-01 22.49.41.jpg

その他、できること

{{ product + '?' }}
{{ firstName + ' ' + lastName }}
{{ clicked ? true : false }}
{{ message.split('').reverse().join('') }}

コンソールから表示を変更できる

データとDOMが関連付けられ、リアクティブに変化することがわかる。

スクリーンショット 2020-09-01 23.02.01.jpg

ディレクティブを使った要素の束縛 (v-bind)

描画された DOM に特定のリアクティブな振舞いを与えます。

以下に例を示しましょう。ここで宣言されているのは、「この要素の title 属性を Vue インスタンスの message プロパティによって更新して保存する」ということになります。

index.html
<div id="app-2">
  <span v-bind:title="message">
    Hover your mouse over me for a few seconds
    to see my dynamically bound title!
  </span>
</div>
main.js
var app2 = new Vue({
  el: '#app-2',
  data: {
    message: 'You loaded this page on ' + new Date().toLocaleString()
  }
})

もうひとつ例を示します。
「この要素の src 属性を Vue インスタンスの image プロパティによって更新して保存する」という意味です。
もちろんこちらもコンソールを使って、app.image = ""で書き換えて上げればリアクティブな書き換えが可能です。

index.html
<div id="app">
    <div class="product">
        <div class="product-image">
            <img v-bind:src="image">
        </div>
        <div id="product-info">
            <h1>{{ product }}</h1>
        </div>
    </div>
</div>
main.js
var app = new Vue({
    el: '#app',
    data: {
        product: 'Socks',
        image: './assets/vsSocks-green.jpg'
    }
})

ディレクティブの省略記法

v-bindを取ってあげるだけで大丈夫です。

元の形 略式
v-bind:alt="description" :alt="description"
v-bind:href="url" :href="url"
v-bind:title="toolTip" :title="toolTip"
v-bindc:class="isActive" :class="isActive"
v-bind:style="isStyeled" :style="isStyeled"
v-bind:disabled="isDisabled" :disabled="isDisabled"
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