0
0

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 1 year has passed since last update.

#Vue 初心者 – 1ファイル内で component を使うごく簡単な例 ( HTML )

Last updated at Posted at 2020-04-30
  • component の中に何を書けば良いかドキュメントから分からない
  • export とか import の例とかに進むとさらによく分からない
  • ごく簡単な例から確認してみよう

  • <li>foo</li><li>bar</li> を component にして <ul> の中で使ってみる
  • script 部分で component を作っておくと、 HTML的なところでタグとして利用することができる
<!-- https://vuejs.org/v2/guide/components-registration.html -->

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.js"></script>
<body>
  <div id="example">
    <ul>
      <list-item-foo></list-item-foo>
      <list-item-foo></list-item-foo>
      <list-item-foo></list-item-foo>
      <list-item-bar></list-item-bar>
      <list-item-bar></list-item-bar>
    </ul>
  </div>

  <script>

    Vue.component('list-item-foo', {
      template: '<li>foo</li>'
    })

    Vue.component('list-item-bar', {
      template: '<li>bar</li>'
    })

   new Vue({
      el: '#example',
    })
</script>
</body>

参考

Vue入門

表示の例

image

一歩進む

Component を生成する時に変数名を付けておいて、それに別の名前をつけて Vue のインスタンスに与えるということが出来るみたいだ

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.js"></script>
<body>
  <div id="example">
    <ul>
      <list-item-foo></list-item-foo>
      <list-item-foo></list-item-foo>
      <list-item-foo></list-item-foo>
      <list-item-bar></list-item-bar>
      <list-item-bar></list-item-bar>
    </ul>
  </div>

  <script>
    var ComponentFoo = Vue.component('list-item-foo', {
      template: '<li>foo</li>'
    })
    var ComponentBar = Vue.component('list-item-bar', {
      template: '<li>bar</li>'
    })

    new Vue({
      el: '#example',
      components: {
        'list-item-foo': ComponentFoo,
        'list-item-bar': ComponentBar
      }
    })
</script>
</body>

別ファイルから import するには?

script から import できるわけではないのだろうか...

まだよく分かっていない

  <script>
    import ComponentFoo from './ComponentA'

エラー

component.html:16 Uncaught SyntaxError: Cannot use import statement outside a module

HTMLファイルや他のファイルだけでは動かなさそうなことが書いてある気もする

image

参考

Vue.jsで単一ファイルコンポーネントを使いたい場合はWebpack等のモジュールバンドラでビルドするのが本来の方法です。しかし、学習コストや環境構築の手間がそれなりにかかります。

【Vue.js】HTML importsを用いた擬似単一ファイルコンポーネント - Qiita

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?