Reputation: 57
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?
Upvotes: 4
Views: 11709
Reputation: 6929
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
Upvotes: 6