Home » vue » How to set a value inside a variable on data() using a function?

How to set a value inside a variable on data() using a function?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m creating a Vue.js component inside a Laravel App.

After I catch the response with an axios request, I can’t put a value inside a variable on method data()

Here is the code:

app.js

require('./bootstrap')

window.Vue = require('vue')

Vue.component('card', require('./components/card.vue'))


let app = new Vue({
    el: '#app'
})

card.vue

<script>
module.exports  = {
    props: [
        'name'
    ],
    data: function() {
        return {
            projects: [],
        }
    },
    mounted() {
        this.getProjects() // NOT WORK?
    },
    methods: {
        getProjects: function() {
            axios.get('/api/v1/getProjects').then(function (response) {

                console.log(response.data)
                this.projects = response.data // NOT WORK

            }).catch(function (error) {

                console.log(error)

            }).then(function () {

            })
        },
    }
}
</script>
Answers:

Try to add .bind(this) or replace function with =>:

getProjects: function() {
        axios.get('/api/v1/getProjects').then((response) => {

            console.log(response.data)
            this.projects = response.data // NOT WORK

        }).catch((error) => {

            console.log(error)

        }).then(function () {

        })
    },

###

It’s because of using this in response callback. You should use an arrow function (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) or save the context in separate variable.