Winston
Winston

Reputation: 331

How to call vue instance outside it in Javascript

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);
            });
        }
    }
});

Upvotes: 24

Views: 45287

Answers (3)

Gerard Carbó
Gerard Carbó

Reputation: 1905

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();    
}

Upvotes: 10

Harsha Basnayake
Harsha Basnayake

Reputation: 4855

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 :)');
  }
},

Upvotes: 7

craig_h
craig_h

Reputation: 32734

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();    
}

Upvotes: 20

Related Questions