-
Notifications
You must be signed in to change notification settings - Fork 22
Another way to fix this: Using Vue.js runtime-only #6
Description
As I understand it, If you use the runtime-only version of vue ( see https://vuejs.org/v2/guide/installation.html#Runtime-Compiler-vs-Runtime-only ), then the compiler is not present in your production environment and the '{{' blocks that might be there from server-side templating will not cause issues.
It is a little tricky to use Vue.js without the compiler when doing server-side templating, I ended up writing a init script like this:
import Vue from 'vue'; // Make sure you are importing the runtime-only version, that is the default but you might have an override changing it
import MyComponent from '../components/my_component.vue'
import AnotherComponent from '../components/another_component.vue'
document.addEventListener('DOMContentLoaded', () => {
// Rather than compiling the whole page with Vue, (which isn't possible anyway
// as we aren't including the compiler), we find the relevant component elements
// individually and instantiate them as standalone Vue apps.
const components = { MyComponent, AnotherComponent }
const instances = [];
for (const component of Object.entries(components)) {
const kebabCaseComponentName = component[0].replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
const componentElements = Array.from(document.querySelectorAll(kebabCaseComponentName));
for (const componentElement of componentElements) {
const propsData = {};
// This applies the attributes from the component dom node to the Vue.js instance
// So we can still pass data from Rails to the components.
for (const attribute of componentElement.attributes) {
propsData[attribute.name] = attribute.value;
}
const ComponentClass = Vue.extend(component[1]);
const instance = new ComponentClass({
el: componentElement,
propsData,
components
});
instances.push(instance);
}
}
})
And you can still use components in your html like: <my-component a-property="somevalue"></my-component>
( I based this code on https://github.com/drewjbartlett/vue-multivue ).
What do you all think of this approach? It works well for us as we had all our templates in .vue files anyway, so losing the runtime compilation was not a big issue.