Home  >  Q&A  >  body text

Vue 3: Composition API, how to call method from component instance?

In Vue 2 I do like this:

import Component from '@/components/Component.vue';

    const VueComponent = {
      install(Vue, settings = {}) {
        const Constructor = Vue.extend(Component);
        const ComponentContainer = new Constructor();
    
        ComponentContainer._props = Object.assign(ComponentContainer._props, settings);
        const vm = ComponentContainer.$mount();
        document.querySelector('body').appendChild(vm.$el);
       }
    }

Then I can call any component method like this:

ComponentContainer.add();

I'm trying to use Vue 3, TS and Composition API to make my component, so I do this:

import { App, createApp, Component } from 'vue';
import ComponentName from './components/ComponentName.vue';

const VueComponentName: Component = {
  install(Vue: App, settings = {}) {
    const ComponentContainer = createApp(ComponentName);
    ComponentContainer._component.props = Object.assign(ComponentContainer._component.props, settings);

    const wrapper = document.createElement('div');
    const vm = ComponentContainer.mount(wrapper);
    document.body.appendChild(vm.$el);
  },
};

In the component I create the method add:

export default defineComponent({
  name: 'ComponentName',
  setup(props, {}) {
    const add = (status) => {
      console.log('test')
    };

    return { add };
  },
});
</script>

Now I want to use the component method in the plugin:

ComponentContainer.add();

But it can't be done, the component instance does not have this method... What did I do wrong?

P粉464208937P粉464208937207 days ago414

reply all(1)I'll reply

  • P粉613735289

    P粉6137352892024-03-26 15:31:35

    In Vue 3, everything declared in the setup method is private to the component. If you want external component/js code to access some of its properties, you must use defineExpose composable.

    export default {
      setup() {
        function add() {...}
    
        defineExpose({ add })
    
        return { add }
      }
    }
    

    Also exists when using the options api: expose

    reply
    0
  • Cancelreply