VueJS accessing externaly imported method in vue component

vue mixin watch
vue-router mixin
vue mixin props
vue 3 mixins
vue mixin global variable
vuejs service
how to add javascript file in vue
vue extends vs mixins

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.

  1. First how do I call this method inside the created life cycle hook to automatically run.
  2. Second how do I call this method by hitting the button "Call External JS"

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.


  1. You can straight-forwardly call the imported something function under any lifecycle method you want. Here, however, I'd recommend using the mounted method, as that's the one that triggers once all of the component's HTML has rendered.

  2. There are lots of ways to do this. One way would be to add the something function under the vue component's data, then call the function directly from the template.

    Personally, I'd make a method on the Vue component which calls the function, then have your template's @click call that method. Doing it this way allows you to perform other actions or call other functions in the future if you wanted to. It also just looks a little cleaner to me.

With that in mind, you'd end up with this:

<template>
  <div>
    <button type="button" name="button" @click="callSomething">Call External JS</button>
    <div id="demo"></div>
  </div>
</template>

<script>
import something from "./something.js"

export default {
  mounted() {
    something()
  },
  methods: {
    callSomething() {
      something()
    }
  }
}
</script>

How to import a external function in a Vue component?, You're exporting an object then in order to use the MyFunction you need to access to that function using dot notation, like this: MyFunctions. With these two lines we can use the library in any component just like we can with Vue Router, Vuex and other plugins that utilise Vue.use. Writing a plugin. Firstly, create a file for your plugin. In this example I'll make a plugin that adds Axios to your all your Vue instances and components, so I'll call the file axios.js.


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.

Access data value via Vue-method from external JS doesn't work , Within this method, I try to access a Vue data value. from an external JS, I want to call a Vue component method. import {EventBus} from '@/event-bus.js' export default { name: 'HelloWorld', data () { return { isOpen: true } }  The API for a Vue.js component essentially comes in three parts - props, events and slots: Props allow the external environment to feed data to the component; Events allow the component to trigger actions in the external environment; Slots allow the external environment to insert content into the component’s view structure.


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>

VueJS accessing externaly imported method in vue component, VueJS accessing externaly imported method in vue component. You can straight-forwardly call the imported something function under any lifecycle method you want. Here, however, I'd recommend using the mounted method, as that's the one that triggers once all of the component's HTML has rendered. There are lots of ways to Since components are reusable Vue instances, they accept the same options as new Vue, such as data, computed, watch, methods, and lifecycle hooks.The only exceptions are a few root-specific options like el.


The methods which are reactive or coupled with the components(which are not API's) should be written in methods.I follow this practice. I have a scenario here to clarify your concepts:

JS file(one with containing function)filename - apis.js

export function GetApiCall(apiName, data, header) {
 return new Promise((resolve, reject) => {
    //do something here
  });
 }

I have used that function here in created hook. Thing is you can use it one of the user-defined methods.

Vue file(one which we will use that function from js file) - filename - infoform.vue

 import { GetApiCall } from '../utils/apisget';
  export default{
    created(){
        // Invoked API to get Data of organization
        GetApiCall(URL,{},{
                "Content-Type": "application/json",
                "Authorization": 'Bearer ' + token
            })
            .then(responseJson => {
            })
            .catch(err=>{
                this.$toasted.show(err);
                // console.log('error==',err);
            });
    },
  methods: {
     onClickMethod () {
       GetApiCall(URL,{},{});
     }
  }
}

Make external function or data accessibles inside the vue methods , Make external function or data accessibles inside the vue methods #91 So, if the client side code can't import code by itself, how should I inject to put your function into a mixin you can access the function from the mixin in object? thats your data see the vue object, thats your configuration of vuejs . Vue.js - The Progressive JavaScript Framework. In many Vue projects, global components will be defined using Vue.component, followed by new Vue({ el: '#container' }) to target a container element in the body of every page.


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>

How to access vue-component methods from vue-custom-element , Issue: I am unable to access vue-component methods from (2) I am using precomplied minified vue.js and vue-custom-element.js into index.html as an external script. Files: I can trigger a vue instance method just in case using $ref in vuejs . //The same MyVueEl instead of importing, define as Object,  import Vue from 'vue' import upperFirst from 'lodash/upperFirst' import camelCase from 'lodash/camelCase' const requireComponent = require.context( // The relative path of the components folder './components', // Whether or not to look in subfolders false, // The regular expression used to match base component filenames /Base[A-Z]\w+\.(vue|js


Add External Scripts, use any external Vue plugin with Gridsome, just import VueTypedJs from '​vue-typed-js' export default function  How can I access a parent method from child component in Vue.js? Posted 4 years ago by chrislentz I am trying to call a parent/root level method on a child component in Vue.js, but I keep getting a message saying TypeError: this.addStatusClass is not a function .


A Beginner's Guide to Working With Components in Vue, component() method of registering a component. Using single-file components generally involves a build step (for example, with Vue CLI). If this  Action handlers receive a context object which exposes the same set of methods/properties on the store instance, so you can call context.commit to commit a mutation, or access the state and getters via context.state and context.getters. We can even call other actions with context.dispatch.


Loading Vuex Modules Dynamically, Loading Vuex Modules Dynamically. Vue.js. By Alex Jover Morales where you'​d want to load a Vuex module dynamically into your app, One could be writing an external component library that depends on You'll then access the $store instance variable, assuming that there's a import state from ". Centralized State Management for Vue.js. What is Vuex? Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.