LoginSignup
0
0

More than 1 year has passed since last update.

【Vue3】別のアプリケーションインスタンスを外部から操作する時に気をつけるべきこと

Posted at

環境

vue 3.1.5

実装したい内容

複数のアプリケーションインスタンスが共存する際、別インスタンスから別のインスタンスを操作したい。

具体的な状況

jsファイルに2つの異なるアプリケーションインスタンス(app1とapp2)が共存する。

const app1 = Vue.createApp({
  data: () => ({
    message: 'instance1'
  }),
  methods: {
  }
})
app1.mount('#app1')

const app2 = Vue.createApp({
  data: () => ({
    message: 'instance2'
  }),
  methods: {
    changeMessage1: function() {
      app1.message = 'changed from instance2'
    }
  }
})
app2.mount('#app2')

app2のmethodsにchangeMessage1関数メソッドを設置し、app2からapp1のmessageを書き換えるような操作を行う。

<body>
  <div id="app1">
    {{message}}
  </div>
  <div id="app2">
    {{message}}
    <button @click="changeMessage1">change message</button>
  </div>
  <script src="https://unpkg.com/vue@3.1.5/dist/vue.global.js"></script>
  <script src="js/hogehoge.js"></script>
</body>

image.png
↑[change message]ボタンを押すことで、instance1という文字列を変更したい。。
が、このままではできない!

直し方

jsファイルを以下のように修正します。

const app1 = Vue.createApp({
  data: () => ({
    message: 'instance1'
  }),
  methods: {
  }
}).mount('#app1')
//------------------
//直接、mountさせる!!
//------------------
const app2 = Vue.createApp({
  data: () => ({
    message: 'instance2'
  }),
  methods: {
    changeMessage1: function() {
      app1.message = 'changed from instance2'
    }
  }
}).mount('#app2')
const app1 = ~
app1.mount('#app1')

と書いていた部分を↓

const app1 = ~.mount('#app1')

のように変更しました。すると、狙い通りに↓
image.png
[change message]ボタンを押すことで、"instance1"から"changed from instance2"とメッセージが変更されました!!

教訓

const app1 = ~
app1.mount('#app1')

これと

const app1 = ~.mount('#app1')

これでは、返り値が異なるためにうまく動かなかったぽいですね。

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