How to call vue instance outside it in Javascript
You are attempting to use this
inside clickit()
where this
refers to window
, so you just need to remove this
and it should call the method inside the view model:
function clickit() { test.fetchTestData(); }
Another way to call VueJs method using external java-script.
Firstly we should create a file. name event.js
import Vue from 'vue';export default new Vue({ data: { }});
After that we should import that event.js to our component
import Event from "../event.js";
Then we can emit an event on our javascript function like below
function yourJavascriptFunction(){ Event.$emit("fetchdata");}
In your component, mounted property should be like below:
mounted() { Event.$on("fetchdata", group => { this.fetchData(); });},methods() { async fetchData() { console.log('hoooray :)'); }},
If you compile this code with 'vue-cli-service build' the variable 'test' will not be defined, but you can make it visible to javascript in the mounted function:
new Vue({ el: '#viewport', data: { test_data: [] }, mounted: function () { window.test=this; }, methods: { fetchTestData: function () { $.get(test.json, function (data) { this.test_data = data; alert(this.test_data.isActive); }); } }});
Then you can call it from javascript:
function clickit() { window.test.fetchTestData(); }