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

3 Answers 3

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();    
}
Sign up to request clarification or add additional context in comments.

Comments

10

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

2 Comments

Works for me, VueJS 2.3.3 version. Thanks.
talk about polluting the global namespace. at least create a namespace for your stuff e.g. window.myNameSpace.test
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 :)');
  }
},

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.