Monday, 22 October 2018

Creating the root Vue instance inside of a Vue file

Is there a way for a .vue file to be responsible for creating its own Vue instance in a Single File Component pattern?

Here's the Vue File.

// MyComponent.vue
<template><div>Hello !</div></template>

<script>
const Vue = require('vue');

// what would usually be exports default
const componentConfig = {
    name: "my-component",
    props: {
        name: String,
    },
};

function create(el, props) {
    const vm = new Vue({
        el,
        render(h) {
            return h(componentConfig, { props });
        });
    vm.$mount();
    return vm;
}

module.exports = { create };
</script>

and then the usage in some JS file:

// index.js
const MyComponent = require('./MyComponent.vue');

const el = '.container';
const props = {
    name: 'Jess',
};

MyComponent.create(el, props);
</script>


When I do the above, I get errors about not being able to find the template.

[Vue warn]: Failed to mount component: template or render function not defined.

found in

---> <MyComponent>
       <Root>

Like instinctually, I don't understand how the Vue compiler would be able to magically deduce (from within the script tags) that I want to reference the template declared above... so.. yeah. Is there an explanation for why I can't do this, or thoughts on how I could get it to work?



from Creating the root Vue instance inside of a Vue file

No comments:

Post a Comment