Load dynamically a vuejs library and render the component on it - javascript

I have a vuejs app as a container for multiple other "apps".
The idea was to:
have a generic code to discover/load components
build the other apps as vuejs lib in order to be able to load component on it
On my first lib, I have this main.js:
import HelloRadar from './components/HelloRadar.vue'
export default HelloRadar
and this component, HelloRadar:
<template>
<div>
Hello from radar !
</div>
</template>
<script>
export default {
name: 'HelloRadar'
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
Now, on my main app, I have this code:
<template>
<div>
<ul>
<li v-for="module in modules" v-bind:key="module" #click="loadModule(module)">
{{ module }}
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'HelloWorld',
data() {
return {
modules: [],
selectedModuleMenu : null,
selectedModuleApp : null
}
},
created: function () {
axios.get("/orbit/api/modules").then((response) => {
var modulesList = response.data;
this.modules = modulesList;
});
},
methods: {
loadModule: function (moduleName) {
this.loadExternalComponent("/modules/" + moduleName + "/"+ moduleName + ".umd.js");
},
loadExternalComponent : function(url) {
const name = url.split('/').reverse()[0].match(/^(.*?)\.umd/)[1];
if (window[name]) return window[name];
window[name] = new Promise((resolve, reject) => {
const script = document.createElement('script');
script.async = true;
script.addEventListener('load', () => {
resolve(window[name]);
});
script.addEventListener('error', () => {
reject(new Error(`Error loading ${url}`));
});
script.src = url;
document.head.appendChild(script);
});
return window[name];
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
The issue is that the function loadExternalComponent seems not working. I got this js error in console:
Uncaught TypeError: Cannot read property 'createVNode' of undefined
Uncaught (in promise) TypeError: Chaining cycle detected for promise #
I have picked this method from here https://markus.oberlehner.net/blog/distributed-vue-applications-loading-components-via-http/
Do you have some idea how to make this kind of app ? Does using lib is the right way ? Thanks for your help

I think there's an answer to your question:
Components built via the Vue 3 vue-cli rely on Vue being available in
the global scope. So in order to render components loaded via the
technique described in my article, you need to set window.Vue to a
reference to Vue itself. Then everything works as expected.
Markus Oberlehner
#moriartie (Markus Oberlehner) has already worked that out with #markoffden: Vue 3 external component/plugin loading in runtime

Related

VueJS; wait for element before running local JavaScript File

I have a few components, javascript, and elements that needs to be ran in a certain order.
1st - opensheetmusicdisplay.min.js which I have in my index.html file. This isn't an issue.
2nd - <div id="xml">
3rd - xml-loader.js which depends on both the "xml" div and opensheetmusicdisplay.min,js
This is the index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<script rel="preload" src="<%= BASE_URL %>js/osmd/opensheetmusicdisplay.min.js"></script>
</head>
<body>
<div id="xml2">words go here</div>
<div id="app"></div>
</body>
</html>
And this is the JavaScript part I'm attempting to test:
window.onload = function() {
alert("xx == ", document.getElementById("xml2"));
}
alert("xx2 == ", document.getElementById("xml2"));
alert(JSON.stringify(opensheetmusicdisplay, null, 1));
When I run this, they both instances of "xml2" show blanks. The opensheetmusicdisplay does show data, which means it is reading from the source in the head section in index.html
It was pointed out to me in the comments that alert only take one argument. That's a mistake that I'm going to let sit for the moment. The error in the console is TypeError: document.getElementById(...) is null.
Now, this is the main.js. There are a lot of comments because of my various ideas:
// vue imports and config
import Vue from 'vue'
import App from '#/App'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
Vue.config.productionTip = false
// page imports
import Notation from '#/components/Notation'
import HomePage from '#/components/HomePage'
// component imports and registration
import { FoundationCSS } from '#/../node_modules/foundation-sites/dist/css/foundation.min.css'
Vue.component('foundation-css', FoundationCSS)
import SideNav from '#/components/SideNav'
Vue.component('side-nav', SideNav);
// import * as Osmd from '#/../public/js/osmd/opensheetmusicdisplay.min.js'
// Vue.component('osmd-js', Osmd)
// import { OsmdJs } from '#/components/Osmd'
import * as XmlJs from '#/../public/js/osmd/xml-loader.js'
Vue.component('xml-js', XmlJs)
// import XLoad from '#/components/XmlLoader'
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/',
components: {
maininfo: HomePage
}
},
{ path: '/chromatic-scales/c-chromatic-scale',
components: {
maininfo: Notation// ,
// xmlloader: XLoad
}
}
]
})
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
I registered XmlJs as global because this is the only way out of 100 things that actually works. I then embed it in Notation.vue like so:
<template>
<div>
<div id="xml">
{{ notation.data }}
</div>
<xml-js />
</div>
</template>
<script>
import axios from 'axios'
export default ({
data () {
return {
notation: null,
}
},
mounted () {
axios
.get('http://localhost:3000/chromatic-scales/c-chromatic-scale')
.then(result => (this.notation = result))
}})
</script>
<style scoped></style>
The last file is the meat and potatoes of what I'm trying to do. The xml-loader.js slurps the data from <div id="xml"> and does whatever magic the program does in order to render the output I want. The issue is that there doesn't seem to be anyway to wait for the stuff in {{ notation.data }}.
I am new to using vuejs and front-end javascript frameworks in general. I do recognize the code is probably not optimal at this time.
There is race condition where DOM element is not available at the time when it's accessed. The solution is to not access DOM elements created by Vue outside of it. DOM element is ready for use only after asynchronous request:
<template>
<div>
<div ref="xml" id="xml">
{{ notation.data }}
</div>
<xml-js />
</div>
</template>
<script>
import axios from 'axios'
export default ({
data () {
return {
notation: null,
}
},
async mounted () {
const result = await axios
.get('http://localhost:3000/chromatic-scales/c-chromatic-scale')
this.notation = result;
this.$nextTick(); // wait for re-render
renderXml(this.$ref.xml); // pass DOM element to third-party renderer
}})
You can import xml-loader.js into the Notation.vue as a function. Then you can simply do something like this:
mounted () {
axios.get(PATH).then(result => {
this.notation = result
let xmlResult = loadXML(result)
doSomethingWithResult(xmlResult)
}
},
methods: {
doSomethingWithResult (result) {
// do something
}
}

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 {{ 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?
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.
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

Cannot Import ES6 module into Vue single file component

I am learning (tinkering with) ES6 modules and Vue.js, single file components (SFC). I built my project with the Vue CLI via the webpack-simple template. I get an error "TypeError: Cannot read property 'name' of undefined" at the line with "settings.mainAlarm.name". "npm run dev" does not throw any errors so I believe the build step is finding (and perhaps ignoring) the settings.js file. What is the best way to import reusable JavaScript into a Vue SFC?
Root.vue file:
<template>
<div id="app">
<h1>{{ msg }}</h1>
<h4>{{ alarmName }}</h4>
</div>
</template>
<script>
//const settings = mainAlarm;
import settings from './lib/settings.js'
export default {
name: 'app',
data () {
return {
msg: 'Welcome to Blah Blah Blah!',
alarmName: settings.mainAlarm.name
}
}
}
//console.log(this.alarmName);
</script>
<style>
</style>
./lib/settings.js file:
export default function () {
var rtn = {
mainAlarm: {
name: "overdueCheckAlarm",
info: { delayInMinutes: .01, periodInMinutes: .25 }
},
notificationAudioFile: "ache.mp3",
baseUrl: "www.xxx.com/xx/xxxx-xxx/"
}
return rtn;
}
Either your settings file should look like this
export default {
mainAlarm: {
name: "overdueCheckAlarm",
info: { delayInMinutes: .01, periodInMinutes: .25 }
},
notificationAudioFile: "ache.mp3",
baseUrl: "www.xxx.com/xx/xxxx-xxx/"
}
in which case, your component will work as is, or your component should look like this and you can leave the settings file alone
<script>
import settings from './lib/settings.js'
// settings.js exports a function as the default, so you
// need to *call* that function
const localSettings = settings()
export default {
name: 'app',
data () {
return {
msg: 'Welcome to Blah Blah Blah!',
alarmName: localSettings.mainAlarm.name
}
}
}
</script>
I expect it's the first option you really want (I'm not sure why you would want a unique settings object every time you use settings, which is what the code in your question would do).

How to import functions from different js file in a Vue+webpack+vue-loader project

I have App.vue which has a template:
<template>
<div id="app">
<login v-if="isTokenAvailable()"></login>
</div>
</template>
I've declared the isTokenAvailable method in the normal way for Vue inside methods. It uses a function that I wrote in a separate js file:
<script>
import * as mylib from './mylib';
export default {
....
methods:{
isTokenAvailable: () => {
return mylib.myfunc();
}
}
}
</script>
mylib starts like this:
import models from './model/models'
import axois from 'axios'
export default function() {
// functions and constants
}
When I run the project, I get this below warning:
export 'myfunc' (imported as 'mylib') was not found in './mylib'
I gather I'm not importing or declaring a javascript module correctly... but there seem to be so many ways to do it, added with the complexity of the scoping in Vue, I'm not sure what is the right way to do it?
Why this isn't a dupe of: How do I include a JavaScript file in another JavaScript file?
That one doesn't seem to fix the problem, specifically in the context of vuejs.
I have tried this:
<script>
const mylib = require('./mylib');
...
</script>
With the function modified to: exports.myfunc = function()
Should I have some other dependency for this to work? Because I get a different error:
[Vue warn]: Error in render function:
TypeError: mylib.myfunc is not a function
Say I want to import data into a component from src/mylib.js:
var test = {
foo () { console.log('foo') },
bar () { console.log('bar') },
baz () { console.log('baz') }
}
export default test
In my .Vue file I simply imported test from src/mylib.js:
<script>
import test from '#/mylib'
console.log(test.foo())
...
</script>
After a few hours of messing around I eventually got something that works, partially answered in a similar issue here: How do I include a JavaScript file in another JavaScript file?
BUT there was an import that was screwing the rest of it up:
Use require in .vue files
<script>
var mylib = require('./mylib');
export default {
....
Exports in mylib
exports.myfunc = () => {....}
Avoid import
The actual issue in my case (which I didn't think was relevant!) was that mylib.js was itself using other dependencies. The resulting error seems to have nothing to do with this, and there was no transpiling error from webpack but anyway I had:
import models from './model/models'
import axios from 'axios'
This works so long as I'm not using mylib in a .vue component. However as soon as I use mylib there, the error described in this issue arises.
I changed to:
let models = require('./model/models');
let axios = require('axios');
And all works as expected.
I like the answer of Anacrust, though, by the fact "console.log" is executed twice, I would like to do a small update for src/mylib.js:
let test = {
foo () { return 'foo' },
bar () { return 'bar' },
baz () { return 'baz' }
}
export default test
All other code remains the same...
I was trying to organize my vue app code, and came across this question , since I have a lot of logic in my component and can not use other sub-coponents , it makes sense to use many functions in a separate js file and call them in the vue file, so here is my attempt
1)The Component (.vue file)
//MyComponent.vue file
<template>
<div>
<div>Hello {{name}}</div>
<button #click="function_A">Read Name</button>
<button #click="function_B">Write Name</button>
<button #click="function_C">Reset</button>
<div>{{message}}</div>
</div>
</template>
<script>
import Mylib from "./Mylib"; // <-- import
export default {
name: "MyComponent",
data() {
return {
name: "Bob",
message: "click on the buttons"
};
},
methods: {
function_A() {
Mylib.myfuncA(this); // <---read data
},
function_B() {
Mylib.myfuncB(this); // <---write data
},
function_C() {
Mylib.myfuncC(this); // <---write data
}
}
};
</script>
2)The External js file
//Mylib.js
let exports = {};
// this (vue instance) is passed as that , so we
// can read and write data from and to it as we please :)
exports.myfuncA = (that) => {
that.message =
"you hit ''myfuncA'' function that is located in Mylib.js and data.name = " +
that.name;
};
exports.myfuncB = (that) => {
that.message =
"you hit ''myfuncB'' function that is located in Mylib.js and now I will change the name to Nassim";
that.name = "Nassim"; // <-- change name to Nassim
};
exports.myfuncC = (that) => {
that.message =
"you hit ''myfuncC'' function that is located in Mylib.js and now I will change the name back to Bob";
that.name = "Bob"; // <-- change name to Bob
};
export default exports;
3)see it in action :
https://codesandbox.io/s/distracted-pare-vuw7i?file=/src/components/MyComponent.vue
edit
after getting more experience with Vue , I found out that you could use mixins too to split your code into different files and make it easier to code and maintain see https://v2.vuejs.org/v2/guide/mixins.html

VueJS data() not working

I am trying to make a VueJS app but I am failing even with the simplest examples.
I am using Laravel 5.3 with pre-built support for VueJS (version 1, I tried version 2 as well).
Here is my Example.vue component
<template>
<div class="profile">
{{ name }}
</div>
</template>
<script>
export default {
data () {
return {
name: 'John Doe'
}
}
}
</script>
And here is the main code
Vue.component('example', require('./components/Example.vue'));
const app = new Vue({
el: '#app'
});
This is the error that shows up everytime in console:
[Vue warn]: Property or method "name" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in component )
Any ideas whats wrong?
Thanks
In your script tags instead of export default use:
module.exports = {
data() {
return { counter: 1 }
}
}
This should work for you
Call the component inside your template
Vue.component('example', {
template: `<div class="profile">{{ name }}</div>`,
data () {
return {
name: 'John Doe'
}
}
})
const app = new Vue({
el: '#app'
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app"><example></example></div>
The problem is that you are trying to load the component 'example' from that file but you didn't give a name to it. You should use:
<script>
export default {
name: 'example',
data() {
return {
name: 'John Doe'
}
}
}
</script>
Or load the component the following way (not sure if extension .vue is needed):
require('./exmaple').default();
If you are using Babel you can also load the components without giving them a name using this syntax:
import Example from ./example
Also checkout this post to get some more info in case you use Babel

Categories