Vue 3: Composition API, how to call method from component instance?
P粉464208937
P粉464208937 2024-03-25 18:57:51
0
1
477

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粉464208937
P粉464208937

reply all(1)
P粉613735289

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template