VueJS accessing externaly imported method in vue component VueJS accessing externaly imported method in vue component vue.js vue.js

VueJS accessing externaly imported method in vue component


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.


  1. 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.

  2. 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 functiondata() {  return {    // some data...    something,  }}

Then in your template use it like:

<template>    <div class="btn btn-primary" @click="something">Do something</div></template>