LoginSignup
7
1

More than 3 years have passed since last update.

new Vue(App) と new Vue({ render: h => h(App) }) の違い

Last updated at Posted at 2019-11-13

結論を先に書きますと、

  • new Vue(App) は、ルートのVueインスタンスになる。
  • new Vue({ render: h => h(App) }) では、{ render: h => h(App) } を元にルートのVueインスタンスが作られ、Appを元にその子が作られる。
  • Vueアプリケーションのオプション(上のAppが指しているObject)には、コンポーネントかどうかという違いはない。親アプリケーションにもコンポーネントにもなれる。

実験

コンポーネントChildと親アプリケーションのParentを作ります。Vueが内部的に使っている_uidを表示します。

child.vue
<template>
  <div>
    <p>Child, {{message}}<br>this: {{_uid}}, $parent: {{$parent && $parent._uid}}, $root: {{$root._uid}}</p>
  </div>
</template>

<script>
export default {
  props: {
    message: {
      type: String, default: 'default'
    }
  }
}
</script>
parent.vue
<template>
  <div>
    <p>Parent<br>this: {{_uid}}, $parent: {{$parent && $parent._uid}}, $root: {{$root._uid}}</p>
    <child message="hello, world"></child>
  </div>
</template>

<script>
import Child from './child';

export default {
  components: { 'child': Child }
}
</script>

ふつうに親アプリケーションを作った場合。

application.js
import Parent from '../parent';

document.addEventListener('DOMContentLoaded', () => {
  new Vue(Parent).$mount('#app');
});

Parentがルートになり、Childが子になります。

結果
Parent
this: 0, $parent: , $root: 0

Child, hello, world
this: 1, $parent: 0, $root: 0

Childを親アプリケーションにした場合。

application.js
import Child from '../child';

document.addEventListener('DOMContentLoaded', () => {
  new Vue(Child).$mount('#app');
});

Childがルートになります。

結果
Child, default
this: 0, $parent: , $root: 0

new Vue({ render: h => h(Child) }) として、さらにpropsを指定した場合。

application.js
import Child from '../child';

document.addEventListener('DOMContentLoaded', () => {
  new Vue({
    render: h => h(Child, { props: { message: 'hello, world' } })
  }).$mount('#app');
});

_uidが0のVueインスタンスが作られ、Childがその子供になります。propsに指定したデータが渡ります。

結果
Child, hello, world
this: 1, $parent: 0, $root: 0

感想:Vue.jsのガイドってVue.jsの基本的な作りが分かりにくいよね。

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