[Vuejs]-How can I change the data value of a Vue app from a method?

0👍

The Vue instance this won’t work inside normal functions that you’re using as callback. That might be the issue in the code. You can either use an arrow function for callback or declare a variable outside assigning the this to the variable, and can use the variable inside the function.

Please check the below code for both solutions

Using an arrow function

async checkIfLoggedIn() {
    var result = null;
    var token = this.getCookie("token")
    var jsonData = {}
    jsonData["token"] = token
    var bodyFormData = new FormData();
    bodyFormData.append('data', JSON.stringify(jsonData));
    await axios({
        method: 'post',
        url: 'backend/index.php?action=checkAuth',
        data: bodyFormData,
        headers: {'Content-Type': 'multipart/form-data'}
    })
        .then((response) => {
            console.log(response);
            if (response.data.status === "OK") {
                this.component = "loggedin"
            } else {
                this.component = "loggedout"
            }
        })
        .catch((response) => {
            console.log(response);
        });
}

Declaring another variable for this

        async checkIfLoggedIn() {
            var result = null;
            var token = this.getCookie("token");
            var jsonData = {};
            jsonData["token"] = token;
            var bodyFormData = new FormData();
            let vue = this;
            bodyFormData.append('data', JSON.stringify(jsonData));
            await axios({
                method: 'post',
                url: 'backend/index.php?action=checkAuth',
                data: bodyFormData,
                headers: {'Content-Type': 'multipart/form-data'}
            })
                .then(function (response) {
                    console.log(response);
                    if (response.data.status === "OK") {
                        vue.component = "loggedin"
                    } else {
                        vue.component = "loggedout"
                    }
                })
                .catch(function (response) {
                    console.log(response);
                });
        }

Leave a comment