LoginSignup
1
3

More than 1 year has passed since last update.

【Vue.js】コンポーネントはLocal登録で使うのが基本

Last updated at Posted at 2021-05-10

はじめに

仕事で使う事になったので1からVue.jsについて学んだ。
ちゃんと覚えておかないとまずそうな事を備忘録として1つ1つ残しておく。

コンポーネントはLocal登録で使うのが基本

前提として、Vue.jsでコンポーネントを定義する方法には以下の2つがある。

# 方法
1 Local登録
2 Global登録

この内、基本的にはLocal登録を用いるようにするべき。
Gobal登録を一般的に用いない理由は、

  • あまり使用されないコンポーネントなのにファイルに残ってしまいファイルサイズが増加する

などの弊害があるため。

※Local登録・Gobal登録いずれも以下の画像のように描画される。
image.png

※Global登録・Local登録の違いは、single file componentをどのように登録して使うか?を見ると分かりやすいかもしれない。
 ・Gobal登録:https://bit.ly/3y6dnUB
 ・Local登録:https://bit.ly/3okHHGz

Global登録の例

Vue.component('my-component',{…})のようにVue.component()でコンポーネントを定義する。
このように定義すると、どこでも<my-component></my-component>で作成したコンポーネントを利用する事ができる。

sample.html
<body>
    <div id="app">
        <my-component></my-component>
        <my-component></my-component>
        <my-component></my-component>
    </div>

    <script src=" https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
    <script>
        Vue.component('my-component', {
            data: function () {
                return { number: 12 }
            },
            template: '<p>いいね({{number}})<button @click="increment">+1</button></p>',
            methods: {
                increment: function () {
                    this.number += 1;
                }
            }
        })

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

Local登録の例

オブジェクトとしてコンポーネントの内容を定義し、それをVueインスタンスのcomponentsプロパティに渡してあげる。
このようにすると、あくまでそのVueインスタンスにおいて<my-component></my-component>でコンポーネントを使えるようになるだけで、他のVueインスタンスで<my-component></my-component>を記載してもコンポーネントは利用できない。

sample.html
<body>
    <div id="app">
        <my-component></my-component>
        <my-component></my-component>
        <my-component></my-component>
    </div>

    <script src=" https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
    <script>
        const component = {
            data: function () {
                return { number: 12 }
            },
            template: '<p>いいね({{number}})<button @click="increment">+1</button></p>',
            methods: {
                increment: function () {
                    this.number += 1;
                }
            }
        }

        new Vue({
            el: '#app',
            components: {
                'my-component': component
            }
        })
    </script>
</body>

Vue.jsの勉強メモ一覧記事へのリンク

Vue.jsについて勉強した際に書いた勉強メモ記事のリンクを集約した記事。

1
3
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
1
3