Home » vue » Vue method not working from inside other method

Vue method not working from inside other method

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a Vue method call error, while I’m trying to call a method from inside an other method of the application:

The JS:

const app = new Vue({
el: '#info',
data() {
    return {
        position: {},
        areas: {}
    };
},
ready() {
},

mounted() {
},
methods: {
    prepareComponent(){

    },
    loadContent(){
        console.log(this.position);
        let queryString = '?lat='+this.position.coords.latitude+'&lon='+this.position.coords.longitude;
        axios.get('/api/getarea'+queryString)
            .then(response => {
                this.areas = response.data;
                this.showAreaData();
            });
    },
    showAreaData(){
        var cities = [];
        for(var area of this.areas){
            cities.push(area.city);
        }
        console.log(cities);
    },
    getLocation(){
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                this.position = position;
                this.loadContent();
            }, function(error) {
                console.log(error);
            });
        }
    },
},
});

and here is the html:

            <div id="info">
                <a href="#" id="getPosition" class="btn btn-link" @click="getLocation">Get Position</a>
                <ul>

                </ul>
            </div>

After running the code, I got an error that loadContent is not defined (TypeError: this.loadContent is not a function).
What am I missing here?

Answers:

try add var _this= this; use _this.loadContent();
or use app.loadContent();

getLocation(){
 var _this= this;
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                this.position = position;
                _this.loadContent();
            }, function(error) {
                console.log(error);
            });
        }
    },

###

this refers to the object that called a function. In the present case, this is navigator.geolocation. You can override the calling object by calling bind on the function:

getLocation(){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            this.position = position;
            this.loadContent();
        }.bind(this), function(error) {
            console.log(error);
        });
    }
}