dayjournal memo

Total 975 articles!!

Riot.js #005 – 繰り返し処理

Yasunori Kirimoto's avatar

riot-js_001_01


今回は、Riot.jsで繰り返し処理をする方法を紹介します。


繰り返し処理をするためには下記のように記述します。


index.html


<!DOCTYPE html>
<html lang="ja">
    <head>

        <meta charset="UTF-8">
        <title>Riot.js sample</title>

        <script src="./library/riot/riot+compiler.js"></script>

        <script src="./tag/sample.tag" type="riot/tag"></script>

    </head>
    <body>

        <sample></sample>
        <sample2></sample2>

        <script>riot.mount('*');</script>

    </body> 
</html>

sample.tag


<sample>

    <p each={list}>{name} {age}</p>

    <style scoped>

        p {
            color: #00AA00;
        }

    </style>

    <script>

        this.list = [
            {
                name: '山田',
                age: '20'
            },
            {
                name: '佐藤',
                age: '30'
            },
            {
                name: '近藤',
                age: '25'
            }
        ];

    </script>

</sample>

<sample2>

    <h1 each={add in list}>{add}</h1>

    <style scoped>

        h1 {
            color: #0D47A1;
        }

    </style>

    <script>

        this.list = [
            'aaa',
            'bbb',
            'ccc'
        ];

    </script>

</sample2>

index.htmlを実行すると下記のようにブラウザで表示されます。

riot-js_005_02


繰り返し処理でオブジェクトをpタグで表示:


    <p each={list}>{name} {age}</p>

    <script>

        this.list = [
            {
                name: '山田',
                age: '20'
            },
            {
                name: '佐藤',
                age: '30'
            },
            {
                name: '近藤',
                age: '25'
            }
        ]

繰り返し処理で配列をh1タグで表示:


    <h1 each={add in list}>{add}</h1>

    <script>

        this.list = [
            'aaa',
            'bbb',
            'ccc'
        ];

    </script>

eachを宣言することによりオブジェクトや配列を繰り返し処理することができます。



book

Q&A