4

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);
       }
    }

And then i can call any component method like this:

ComponentContainer.add();

I'm trying to make my component using Vue 3, TS and Composition API, 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);
  },
};

And in component i create method add:

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

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

Now i want to use component method from the plugin:

ComponentContainer.add();

But can't do it, the component instance doesn't have this method... What am i do wrong?

1 Answer 1

6

Note: I'm not sure why you're doing all this stuff, it looks a bit dark and overcomplicated for a vue component!

In Vue 3, everything declared within the setup method is private to the component. If you want an external component / js code to access some of its properties, you have to explicitly declare it using the defineExpose composable.

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

    defineExpose({ add })

    return { add }
  }
}

It also exists when using option api: expose

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.