I am trying to load a custom JS file into my vue and I recently came across vue-plugin-load-script and installed it. I configured it as below:
In my main.js I have
Vue.loadScript("file.js").then(() => {
console.log("SUCESS")
}).catch(() => {
console.log("FAILED")
})
however, the npm page does not show how to use your functions in your views. For instances, lets say the file.js had a function called calculateTime(), and I have a view called Home.vue. How would I call the calculateTime() function from my
<script>
export default {
methods : {
** Trying to put function here **
}
}
</script>
If you have you JS File local, you can import it, like:
import * as localA from "./../../theFile.js"; /*put your path to file.js*/
And after that you can use all methods from theFile.js by writting in a method from your vue Component
methodVue: function (...) {
localA.theMethod(param); /*the Method is declared in theFile.js*/
return;
}
And in your theFile.js your method that you want to use need to be written like that
export function theMethod(param) {
...
}
Do you have a specific reason to use this library? Looking at the function all it does is add a script tag to the DOM if it is not already there and resolve the promise when it loads GitHub link. You could just as well use import * from 'file.js' at the top of the vue file. Then use the functions from that file as usual. The bundler should be able to figure out if the file is imported in multiple places and add it only once.
Related
I'm using Laravel with Vite. But I'm having a trouble. I have multiple JS files and including them whenever I want to use. But I cannot use the function I created in one file in another file.
I have an app.js file looks like this:
import jQuery from 'jquery';
window.$ = jQuery;
import './bootstrap';
import './main.js';
import Alpine from 'alpinejs';
window.Alpine = Alpine;
Alpine.start();
And I have a function like this in main.js:
function testFunction() {
alert('test');
}
I put Vite definitions to my layout blade like this:
#vite(['resources/css/app.css', 'resources/js/app.js'])
I have another page contains another JS file like this:
#extends('layouts.app')
#section('content')
#endsection
#section('scripts')
#vite(['resources/js/edit-note-page.js'])
#endsection
And in that JS file I want to use the function that I mentioned in the beginning like this:
testFunction();
But I'm getting an Uncaught ReferenceError: testFunction is not defined error in console. I couldn't figure it out. What is the correct way to do it?
I'm using Laravel with Vite. I have multiple JS files and including them whenever I want to use. But I cannot use the function I created in one file in another file.
Each file is going to be wrapped to actually prevent what you are attempting to do, unless explicitly defined on the window object (notice how window.Alpine = Alpine; is set in your app.js). An alternative and more modern way is to use exports. Here is an example using your file structure.
main.js:
function testFunction() {
alert('test');
}
export default testFunction;
edit-note-page.js:
import testFunction from './path/to/file/name';
...code here
The path to the file in the import does not need the extension .js at the end.
Note: After this change, you no longer need import './main.js'; inside of app.js
I have a function inside a .js file in a nuxt 2 project.
Basically I need to use a nuxt module property from nuxt.config like this this.nuxt.options. inside a function in a normal .js file.
For example:
aNormalJsFile.js
if (this.nuxt.options.module.triggers.isActive) {
// do something
}
But now I can't because it doesn't know what is Nuxt of course. I'm getting this error:
Cannot read properties of undefined (reading 'nuxt')
If you want to inject a Vue/Nuxt instance inside of a .js file (vanilla JS), you can follow this helper function approach
/src/utils/printCoolNumber.js
export const printIt = (VueInstance) => console.log(VueInstance.coolNumber)
// ☝🏻 basically does console.log(this.coolNumber) as in a .vue file
Any .vue file
<script>
import { printIt } from "#/utils/printCoolNumber";
export default {
data() {
return {
coolNumber: 12,
};
},
mounted() {
printIt(this) // 👈🏻 Vue instance ("this") passed here, it prints 12 in the console
},
};
</script>
I wouldn't say that this is the best approach in the long run (using Composables is usually still better) but it is great for small helper functions where you don't need too much Vue-specific methods.
I have tried exporting some functions to the main.js file in scalajs using #JSExportTopLevel annotation, as explained in the Export Scala.js APIs to JavaScript scalajs documentation and building the main.js as explained here.
This results in main.js from which I am able to make use the functions exported in the scalajs code.
Now I want to use these exported functions in my reactjs components. For this I tried following steps:
Copy the main.js file in the public folder
Include the javascript file in the index.html, like so:
<script type="text/javascript" src="./main.js"></script>
Now, if I load the app in the browser and try to use these functions in the browser console, it works fine:
console.log(foo());
But I am not the utilise these functions in reactjs components:
import React from 'react';
const RuleEditor = () => {
console.log(foo());
return (
<>
</>
);
};
export default RuleEditor;
I always get the following compilation error:
foo is not defined no-undef
I do understand that reactjs is not able to recognise the function as I haven't really specified where to get that function from but I am not really sure how to achieve it. I have gone to couple of other stackoverflow posts where some suggestions where to look for it in window object but I didn't find those functions there.
Please suggest a proper way to make use of functions exported from scalajs in reactjs components. TIA.
Exporting objects/classes/functions as top level exports put them in Javascript global scope.
class Foo(val x: Int) {
#JSExport
def square(): Int = x*x // note the (), omitting them has a different behavior
#JSExport("foobar")
def add(y: Int): Int = x+y
}
You can utilise these functions in the scripts embedded in html or in scalajs as shown here.
But if you need to use these functions in a nodejs app, you need to export these functions from a module. We need to add the following in the build.sbt. Read more here.
scalaJSLinkerConfig ~= { _.withModuleKind(ModuleKind.ESModule) }
Now, we can make use of the exported functions in a nodejs app by importing them like so:
import { square, add } from './main'
If you wish to export these functions from a module named other than main, provide module id for each exported function like so:
class Foo(val x: Int) {
#JSExport("square", "my-math")
def square(): Int = x*x // note the (), omitting them has a different behavior
#JSExport("foobar", "my-math")
def add(y: Int): Int = x+y
}
and use it like so:
import { square, add } from './my-math'
I have put my js files eva.min.js/feather.min.js and so on in vendor dir, then I imported them in ember-cli-build.js app.import('vendor/eva.min.js'). But how to use it?
I tried something like import eva from 'eva'/'eva.min'/'eva.min.js' or import Eva from 'eva'; and so on, but it doesn't work.
app.import('vendor/eva.min.js');
app.import('vendor/bootstrap.min.js');
app.import('vendor/feather.min.js');
app.import('vendor/popper.min.js');
app.import('vendor/jquery-slim.min.js');
app.import('vendor/swipe.js');
import Swipe from 'swipe';
Console usually gives me the could not find the module error.
And I don't have a deep background in programming, so I would highly appreciate if you explained the problem as simple as possible.
UPD: I found all js code as npm package (it happens that the js files weren't third-party)
https://www.npmjs.com/package/feather
https://www.npmjs.com/package/popper.js
https://www.npmjs.com/package/jquery-slim
https://www.npmjs.com/package/swipe
https://www.npmjs.com/package/bootstrap
https://www.npmjs.com/package/eva-icons
But all your responses were helpful. Anyway in the near future I expect to use third-party libraries.
A quick way is to use scriptjs and it allows you to load any javascript into your component in the following way: (I am using Yammer as an example)
import $scriptjs from 'scriptjs';
componentDidUpdate() {
//script loader
setTimeout(function(){
$scriptjs('https://c64.assets-yammer.com/assets/platform_embed.js',
() => {
window.yam.connect.embedFeed(YammerHelper.loadComments());
});
}, 1000);
}
You should get the idea how to consume it. Check their docs with lots of examples.
This is not the best solution. But one way of using the third party js is,
1) say you have a function in your js file vendor/third-party.js
someFunction = function (element) {
...
console.log("works")
};
2) Then import it in your ember-cli-build.js
...
app.import('vendor/third-party.js');
...
3) After importing restart your server.
Use the function directly in your controller/component as
window["someFunction"]
Unless the JavaScript library being used explicitly supports the import X from 'y' syntax then when you import in the build using the app.import syntax you just use it in your app just as the plugin documentation describes.
So for Swipe you would do the following.
Based on this documentation: https://github.com/thebird/Swipe
// ember-cli-build.js
app.import('myswipe.js`);
// component.js
/* global Swipe */ // This silences the linter from throwing errors...
classNames: ['swipe'],
didInsertElement() {
this._swipe = Swipe(this.element, {
option1: option1
});
}
// component.hbs
<div class='swipe-wrap'>
{{yield}}
</div>
This codes creates a component to control your swipe plugin.
This code would create a swipe object and isolate it to the component.
Again when you use the app.import you are just loading the library on boot. The library does whatever it says it will do in the docs. Sometimes they register a global object, sometimes they dont.
I'm making an Api repository for my Vue.js application, following this article.
Thing is, I like to document my functions so I have better code completion on VSCode. I typically use jsDoc for this.
I'm stuck here:
import DiarioEscolarRepository from './diarioEscolarRepository';
import PeriodoAvaliativoRepository from './periodoAvaliativoRepository';
import AtividadeAvaliativaRepository from './atividadeAvaliativaRepository';
import CorteEtarioRepository from './corteEtarioRepository';
const repositories = {
diarioEscolar: DiarioEscolarRepository,
periodoAvaliativo: PeriodoAvaliativoRepository,
atividadeAvaliativa: AtividadeAvaliativaRepository,
corteEtario: CorteEtarioRepository,
};
export default const RepositoryFactory = {
get(name){
return repositories[name];
}
};
I need to make it so the editor understands that the get function is a simple acessor to the repositories object.
I tried using #typedef and #type, but none of them worked properly.
I tried something like #returns {repositories.name}, but is also does not work.
Is there a way to document this?
I also thought about using a typescript definition file but I never did it, so I don't know where to begin.