LoginSignup
21
22

More than 5 years have passed since last update.

Riot.jsのカスタムタグを使わずに、divタグでmountして使う方法

Last updated at Posted at 2015-05-02

Riot.jsは今流行りのReact.jsライクで比べて軽量なライブラリーです。
React.jsに比べてシンプルで簡単に導入できるので、Reactには興味あるけどなんか難しそうって方にもおすすめなライブラリー。

詳しくはこちら↓

Riot公式
Riot.js 2.0 情報まとめ

Riot.jsを使っている中で
ちょっとネックになるのがカスタムタグの存在です。

例えばこんなソースコード場合、

<body>
  <hello></hello>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/riot/2.0.15/riot+compiler.min.js"></script>
  <script type="riot/tag">
    <hello>
      <h1>{ title }</h1>

      this.title = "hello world!"
    </hello>
  </script>
  <script>
    riot.mount("hello")
  </script>
</body>

この場合は実行すると<hello>タグの{title}部分に"hello world!"という文字列に流し込まれます。

この<hello>の部分がRiot.jsで使われるカスタムタグになります。
しかし、HTML的に気持ち悪い部分です。IE対応もめんどくさい・・・

そこで、Riot.jsではちゃんと通常のHTMLのタグでもmountingできるような機能が用意されています。

<body>
<div id="hello"></div>
<div class="world"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/riot/2.0.15/riot+compiler.min.js"></script>
<script type="riot/tag">
  <hello>
    <h1>{ title }</h1>

    this.title = "hello world!"
  </hello>
</script>
<script>
  riot.mount("#hello", "hello")
  riot.mount(".world", "hello")
</script>
</body>

riot.mount()の第1引数にセレクター、第2引数にriotのカスタムタグを指定することで対応可能です。
セレクターにはjQueryのようにidは『#』、classは『.』から始まるものが使えます。

こんな感じで、Riot.jsのカスタムタグを使わずに普通のdivタグでmountして使うことができました。

ちなみに

  riot.mount("#hello, .world", "hello")

のようにまとめて書くこともでできます。

21
22
1

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
21
22