24

How can I call the test vue in javascript? Here is my code, I want to call test when I do something in javascript function.

function clickit() {
   this.test.fetchTestData();    
}

var test = new Vue({
    el: '#viewport',
    data: {
        test_data: []
    },

    mounted: function () {
        this.fetchTestData();
    },

    methods: {
        fetchTestData: function () {
            $.get(test.json, function (data) {
                this.test_data = data;
               alert(this.test_data.isActive);
            });
        }
    }
});
Vini.g.fer
  • 11,639
  • 16
  • 61
  • 90
Winston
  • 321
  • 2
  • 3
  • 9
  • Possible duplicate of [Call a Vue JS component method from outside the component](http://stackoverflow.com/questions/33682651/call-a-vue-js-component-method-from-outside-the-component) – Saurabh Nov 23 '16 at 09:33

3 Answers3

20

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();    
}
craig_h
  • 31,871
  • 6
  • 59
  • 68
9

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();    
}
Gerard Carbó
  • 1,775
  • 18
  • 16
7

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 :)');
  }
},
Harsha Basnayake
  • 4,565
  • 3
  • 17
  • 23