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.

ローカルコンポーネントとグローバルコンポーネント

Last updated at Posted at 2022-08-04

定義

ローカルコンポーネントとは

特定のVueインスタンス内でしか使えないようなコンポーネント

グローバルコンポーネントとは

どのインスタンスでも使うことができるコンポーネント

コンポーネントの使い方

ローカルコンポーネント、グローバルコンポーネント共にhtmlは共通で以下のように設定する。

html
<div id="app">
  <p>インスタンス1:</p>
  <my-component></my-component>
</div>

ローカルコンポーネント

javascript
var MyComponent = {
  template: `
    <form>
      <input type="text">
      <button type="submit">送信</button>
    </form>
  ` 
}
var vm = new Vue({
  el: "#app",
  components: {
    'my-component': MyComponent
  }
})

「var vm」でインスタンスを生成し、それに対して「My Component」のローカルコンポーネントを割り当てている。

グローバルコンポーネント

javascript
Vue.component("my-component", {
  template: `
    <form>
      <input type="text">
      <button type="submit">送信</button>
    </form>
  `
})
const mv = new Vue({
  el: '#app'
})

「Vue.component」でコンポーネントを生成しており、「const mv」とは直接関連していない。

ローカルとグローバルの違い例

ローカルとグローバルで具体的な使い方を参考にどのような部分に違いが出てくるのかを検証してみる。

ローカルコンポーネント

html
<div id="app">
  <p>インスタンス1:</p>
  <my-component></my-component>
</div>
<div id="app2">
  <p>インスタンス2:</p>
  <my-component></my-component>
</div>
javascript
var MyComponent = {
  template: `
    <form>
      <input type="text">
      <button type="submit">送信</button>
    </form>
  ` 
}
var vm = new Vue({
  el: "#app",
  components: {
    'my-component': MyComponent
  }
})
var vm2 = new Vue({
  el: "#app2"
})

image.png

「app」の方ではコンポーネントを設定しているが、「app2」の方ではコンポーネントを設定していないため、インスタンス1のみに送信フォームが表示されている。

グローバルコンポーネント

html
<div id="app">
  <p>インスタンス1:</p>
  <my-component></my-component>
</div>
<div id="app2">
  <p>インスタンス2:</p>
  <my-component></my-component>
</div>
javascript
Vue.component("my-component", {
  template: `
    <form>
      <input type="text">
      <button type="submit">送信</button>
    </form>
  `
})
const mv = new Vue({
  el: '#app'
})
const mv2 = new Vue({
  el: '#app2'
})

image.png

この場合はどちらのインスタンスでも生成することができる。

リンク

第20回 Vue.js入門 グローバルコンポーネントとローカルコンポーネント

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?