4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Vuejs】v-forで配列を出力する時に1つ目の要素とそれ以降でstyleを変える

Last updated at Posted at 2020-02-16

テーブルとかもそうですが、最初の要素だけスタイルを切り替えたい時にどうするんだろうと調べていたら3項演算子が使えました。

#class属性を配列の要素番号で切り替える

sample.html
    <style>
        .first{
            color: aquamarine;
        }
        .two-or-more{
            color: burlywood;
        }
    </style>
    <div id="app">
        <ul>
            <li v-for="(e,index) in mylist" v-bind:class="[index == 0 ? 'first' : 'two-or-more']">{{e.name}}</li>
        </ul>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el: "#app",
            data: {
                mylist: [
                    { name: "1つ目" },
                    { name: "2つ目" },
                    { name: "3つ目" },
                    { name: "4つ目" },
                ],
            }
        })
    </script>

#結果
画面はこんな感じで、
Screenshot2020-02-16_20-09-52.png

要素はこんな感じで出力されました。
Screenshot2020-02-16_20-13-42.png

#参考
公式ドキュメント#配列構文
https://jp.vuejs.org/v2/guide/class-and-style.html#%E9%85%8D%E5%88%97%E6%A7%8B%E6%96%87

4
6
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
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?