LoginSignup
0
0

More than 3 years have passed since last update.

Vue.js v-bind の使い方(属性の扱いにも触れてます)

Last updated at Posted at 2020-07-15

v-bindの使い方についての備忘録

参考記事
https://www.youtube.com/watch?v=qzFJfekigY8&list=PLh6V6_7fbbo-SZYHHBVFstU2tp0dDZMAW&index=4

コード

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .abc{
            color:red;
        }
        .abc2{
            background: blue;
        }
    </style>
</head>
<body>
    <h1>Vueの練習</h1>
<div id="app">
  <!-- <p class='error'>エラーです</p> -->
  <!-- <p class='{{error_class}}''>エラーです</p> -->
  <!-- ↑このように属性の中にマスタッシュ記法は出来ない。マスタッシュはhtmlタグに書かなくては機能しない -->
<!-- classの中に書きたいときは以下のような記法がある ↓-->
<p v-bind:class='error_class'>エラーです</p>


</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>

let app = new Vue({
    el:'#app',
    data:{
        error_class:'abc abc2',
        img_src:'https://cdn.pixabay.com/photo/2020/07/06/13/21/porsche-5377019__480.jpg'
    }
});



</script>
</body>
</html>

ポイントは
属性にはマスタッシュ記法が使えない

<p class='{{error_class}}''>エラーです</p> 

↑これのこと。この書き方は❌(マスタッシュが属性の中にある)

マスタッシュが使えるのはhtmlタグである。

<div id="app">{{test+count}}</div>

↑こういうのはOK(マスタッシュがhtmlタグ内にある)
では属性(タグ内のclassやimgタグのsrcなどをVueでいじるにはどうすれば良いか、、、

そこで使用するのが「v-bind」
使い方は以下
html側

<div id="app">
<p v-bind:class='error_class'>エラーです</p>
<img v-bind:src="img_src">
</div>

js側


let app = new Vue({
    el:'#app',
    data:{
        error_class:'abc abc2',
        img_src:'https://cdn.pixabay.com/photo/2020/07/06/13/21/porsche-5377019__480.jpg'
    }
});

Vueの記法内のdataで変数を設定(error_classとimg_src)。
そこに属性に当てたい内容を記述する。
これでcssや画像のURLをVueで指定することが出来る。

結果は以下
スクリーンショット 2020-07-15 21.22.42.png

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