I have an External Java Script File something.js
function myFun(){
document.getElementById("demo").innerHTML="Hello World!";
}
export default myFun;
and this is my vue component Dashboard.vue
<template>
<div>
<button type="button" name="button" @click="">Call External JS</button>
<div id="demo"></div>
</div>
</template>
<script>
import something from "./something.js"
export default {
created(){
}
}
</script>
I have two questions.
Of-cause I know to change the content of a div can easily done by vueJS without the help of pure JS external files. But I'm asking this question for clarify the concepts of how do I use external JS files inside the vue component.
Thank you.
A better solution would be to to use mixins:
import something from './something.js'
export default {
mixins: [something]
}
now you can use whatever methods / computed you have exported in something.js
, directly on this
.
So, in your example, you have myFun()
exported from something.js
, and we can call it from Dashboard.vue
like so:
<template>
<div>
<button type="button" name="button" @click="myFun">Call External JS</button>
<div id="demo"></div>
</div>
</template>
<script>
import something from "./something.js"
export default {
mixins: [something],
mounted(){
this.myFun()
}
}
</script>
I hope I got the syntax right, but that's generally the idea of mixins.
You can call the imported something
function under any lifecycle method you want. Here, I'd recommend using the mounted
method. That triggers once all of the component's HTML has rendered.
You can add the something
function under the vue component's methods, then call the function directly from the template.
<template>
<div>
<button type="button" name="button" @click="something">
Call External JS
</button>
<div id="demo"></div>
</div>
</template>
<script>
import something from "./something.js"
export default {
mounted() {
something()
},
methods: {
something,
},
}
</script>
Another approach would be to add the method in the data-block:
import something from "./something.js" // assuming something is a function
data() {
return {
// some data...
something,
}
}
Then in your template use it like:
<template>
<div class="btn btn-primary" @click="something">Do something</div>
</template>
With your example, external javascript file something.js
function myFun(){
document.getElementById("demo").innerHTML="Hello World!";
}
export default myFun;
You can parse it like object in your methods:{} in Dashboard.vue
<template>
<div>
<button type="button" name="button" @click="something">Call External JS</button>
<div id="demo"></div>
</div>
</template>
<script>
import something from "./something.js"
export default {
methods: {
something,
}
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With