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?
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 usedefineExpose
composable.Also exists when using the options api:
expose