0

My Vue 3 application is as follow:

app.js

import { createApp } from "vue";
import App from "./app.vue";

let vm = createApp(App)
vm.mount("#app");

window.vm = vm

app.vue

<script>
export default {
  name: "App",
  methods: {
    async someMethod() {
      this.data.push(1);
    }
    //...

}
</script>

In Vue 2, it is possible to reach internal methods using the following code:

vm.$children[0].someMethod()

However, it does not work with Vue3.

How can I integrate my Vue component to an external API using a similar technique in Vue 3?

h3xStream
  • 6,293
  • 2
  • 47
  • 57
  • It's a bad practice to access internals through $children. If you need to affect the app from the outside, it should expose public method that interacts with children. In your case no children are involved, `vm` is App comp instance and it should be vm.someMethod().There's at least one mistake, createApp returns app instance and not comp instance. It should be `vm = app.mount("#app")` – Estus Flask Mar 27 '23 at 20:16
  • @EstusFlask I'm not sure how to make methods from the root component **public**. `vm.someMethod()` does not work. I only see `vm._container`, `vm._component`, `vm._context` ... – h3xStream Mar 27 '23 at 20:29
  • 2
    See the previous comment. `vm` is wrong – Estus Flask Mar 27 '23 at 20:48

2 Answers2

1

This question was answered by Estus Flask in the comments section.

app.js

import { createApp } from "vue";
import App from "./app.vue";

let app = createApp(App)
let vm = app.mount("#app"); //This return instance is the proxy to the VueJs component

window.vm = vm;
h3xStream
  • 6,293
  • 2
  • 47
  • 57
1

In Vue 3, to access the internal methods of a component, you should consider using defineExpose to expose the method in that component

https://vuejs.org/api/sfc-script-setup.html#defineexpose

KitKit
  • 8,549
  • 12
  • 56
  • 82