9

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 {{ name }}!</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?

Jess
  • 3,097
  • 2
  • 16
  • 42
  • 2
    Your question seems to be that you want to instantiate Vue on the component instead of in index.js. That is definitely counter to the main pattern Vue sets forth. Why do you want to do that? – For the Name Oct 22 '18 at 17:16
  • We have a larger system where multiple root Vue instances will be in control of individual parts of a page. There is no one "index.js" file in our case, we have many sections of a page that must be managed individually. That, in combination with using Vue in an existing code base (because starting greenfield is a dream, right?) means that we want to give the direct usages of Vue a single home. So we settled on the thought that the components that are entry points to the rest of the Vue stack could encapsulate the setting up and tearing down of their own root Vue instance. – Jess Oct 23 '18 at 15:51
  • We're also a plugin, so we have limitations of when we can instantiate and the type of environment we can assume. As a plugin, using a framework is an interesting problem and we're trying to stick to the textbook/most-supported path of Vue as much as possible... Although encapsulating the mounting and setup of a Component's root vue instance was a desire my group mentioned. So we're looking into it. – Jess Oct 23 '18 at 15:53

2 Answers2

4

What you are describing is done in a pre-compilation step through Webpack and Vue Loader. The Vue compiler doesn't actually parse Single File Components. What the Vue compiler can parse is templates provided in a component’s options object. So if you provide a template option in your componentConfig object your example will work. Otherwise you'll have to go through the pre-compilation step with Webpack and Vue Loader to parse a Single File Component's template. To do that you'll have to conform to the SFC structure defined in the spec. Here's an excerpt ..

Template

  • Each *.vue file can contain at most one <template> block at a time.
  • Contents will be extracted and passed on to vue-template-compiler and pre-compiled into JavaScript render functions, and finally injected into the exported component in the <script> section.

Script

  • Each *.vue file can contain at most one block at a time.
  • The script is executed as an ES Module.
  • The default export should be a Vue.js component options object. Exporting an extended constructor created by Vue.extend() is also supported, but a plain object is preferred.
  • Any webpack rules that match against .js files (or the extension specified by the lang attribute) will be applied to contents in the <script> block as well.

To make your specific example work You can re-write main.js file like this ..

const MyComponent = require("./MyComponent.vue");

const el = ".container";
const data = {
  name: "Jess"
};

MyComponent.create(el, data);

And your MyComponent.vue file (This could just as well be a js file as @Ferrybig mentioned below) ..

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

function create(el, data) {
  const componentConfig = {
    el,
    name: "my-component",
    data,
    template: `<div>Hello {{ name }}!</div>`
  };
  const vm = new Vue(componentConfig);
  return vm;
}

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

See this CodeSandbox

Or if you prefer render functions your MyComponent.vue will look like this ..

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

function create(el, data) {
  const componentConfig = {
    el,
    name: "my-component",
    data,
    render(h) { return h('div', 'Hello ' + data.name) } 
  };
  const vm = new Vue(componentConfig);
  return vm;
}

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

CodeSandbox


One last thing to keep in mind: In any component you can use either a template or a render function, but not both like you do in your example. This is because one of them will override the other. For example, see the JSFiddle Vue boilerplate and notice how when you add a render function the template gets overridden. This would explain that error you were getting. The render function took precedence, but you fed it a component's options object that provides no template to be rendered.

tony19
  • 125,647
  • 18
  • 229
  • 307
Husam Ibrahim
  • 6,999
  • 3
  • 16
  • 28
  • Both of your examples can be `.js` files, as you are not using any `.vue` functions – Ferrybig Oct 22 '18 at 18:36
  • 1
    @Ferrybig I was providing an ad hoc solution to the OP's example. I did mention that SFCs can only be used in combination with Vue Loader, which obviously requires a certain structure for authoring components as defined in the [spec](https://vue-loader.vuejs.org/spec.html). I guess I have to make that clearer in my answer. Thanks :) – Husam Ibrahim Oct 22 '18 at 19:30
  • So if I wanted to reference the `` content from within the componentConfig I would start hacking around in the `vue-template-compiler` and playing with the render function that it exports. Cool. Disclaimer: definitely not gonna do that bc it would be unmaintainable longterm, but just curious.. – Jess Oct 23 '18 at 15:59
  • You can see the comments under my question for my motivation to do this pattern. – Jess Oct 23 '18 at 16:00
  • @Jess You'll have to come up with a workaround to export an object in the format that Vue Loader expects. Other than that I'm afraid I can't think of anything short of forking Vue Loader. – Husam Ibrahim Oct 23 '18 at 21:30
  • @HusamIbrahim yeah, it's looking that way. Thank you for the context and the insight into how the templates are compiled. – Jess Oct 23 '18 at 23:48
3

You are really close to a working solution, but you are missing just some "glue" parts to combine everything together:

<template>
    <div>Hello {{ name }}!</div>
</template>
<script>
    import HelloWorld from "./components/HelloWorld";
    import Vue from "vue";

    const Component = {
        // Add data here that normally goes into the "export default" section
        name: "my-component",
        props: {
            name: String,
        },
        data() {
            return {
            };
        },

    };
    Component.create = function(el, props) {
        const vm = new Vue({
            el,
            render(h) {
                return h(Component, { props });
            },
        });
        vm.$mount();
        return vm;
    };
    export default Component;
</script>

This can then be used as follows in other files:

import App from "./App";
App.create("#app", {
    name: 'Hello World!',
});

Example on codesandbox: https://codesandbox.io/s/m61klzlwy

Ferrybig
  • 18,194
  • 6
  • 57
  • 79
  • This is pretty close to what I want... and is possibly good enough. I think the difference is that the (maybe impossible) dream is that `HelloWorld` could be the template... given that I would only ever have one component at the root level. – Jess Oct 23 '18 at 23:47