Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
            });
        }
    }
});
like image 315
Winston Avatar asked Nov 23 '16 08:11

Winston


2 Answers

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();    
}
like image 192
craig_h Avatar answered Oct 08 '22 19:10

craig_h


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 :)');
  }
},
like image 28
Harsha Sampath Avatar answered Oct 08 '22 19:10

Harsha Sampath