4
5

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 5 years have passed since last update.

【Vue.js】複数のインスタンスを作成する方法【初心者】

Last updated at Posted at 2020-07-15

現在Vue.jsを勉強しています。
Appというインスタンスの他にpage2というインスタンスを作成しようと思います。

vueファイル内でnew Vueと書くことはできないので、main.jsnew Vueを書くことによって複数のインスタンスを作成します。

コンポーネントを他のコンポーネントでも使えるようにするには、script内をexport defaultで囲むことによってvueインスタンスを生成します。したがって、基本的にscriptの部分は export default で囲むことが前提となります。(なんか足りてない、または間違っている気がするので見直してみます。)

参考:export defaultについて

main.js

・main.jsにnew Vueを書くことによって複数のインスタンスを作成します。
・作成するpage2をインポートする必要があります。

main.js
import Vue from 'vue'
import App from './App.vue'
import page2 from './components/page2.vue'
import router from './router'

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

new Vue({
  router,
  render: h => h(page2),
}).$mount('#page2')

page2.vue

・id はpage2とする必要があります。
・script内のexport defaultで下記を記述する必要があります。

name: 'page2',
  components: {
  }
}
page2.vue

<template>
  <div id="page2">
<router-view></router-view>


ああああ
  </div>

</template>


<script>
export default {
  name: 'page2',
  components: {
  }
}
</script>

これで、元々あったAppに加え、page2という2つのインスタンスをアプリ内に作成することができました。

4
5
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?