Initially, it appears that you are applying a click handler in the "Vue" manner, even though it is not actually within a Vue component. This approach will not be effective.
To properly achieve your desired outcome, you must expose your function to a different scope by assigning it to a window attribute.
var viewModel = new Vue({
el: "#app",
data: {},
created () {
// The function is now accessible
window.test = this.test;
},
methods: {
test: function() {
alert("test function called");
}
}
});
// Later on
window.test();
A more optimal solution would be to utilize a global event bus. Instead of exposing arbitrary functions globally, you can create a bus for communication. This allows for emitting events within the Vue application using this.$bus.$emit('...')
and listening to them throughout the application. By employing a defined interface between the internal and external parts of the Vue application, unnecessary exposure of functions in the global scope is avoided, enabling better control over interactions with the application from outside sources.
import Vue from 'vue';
export const bus = new Vue();
// In another file
import { bus } from './bus';
Vue.prototype.$bus = bus;
// External code usage
import { bus } from '../../my-vue-application/bus';
bus.$emit('test');
// Within a component
var viewModel = new Vue({
el: "#app",
data: {},
created () {
this.$bus.$on('test', this.test);
},
beforeDestroy () {
this.$bus.$off('test', this.test);
},
methods: {
test: function() {
alert("test function called");
}
}
});