[Vuejs]-Vue.js method โ€“ Access to `this` within lodash _each loop

0๐Ÿ‘

โœ…

Try replace function to arrow function with lexical context:

methods: {
    remove: () => {
        if (confirm('Are you sure you want to delete these collaborators?')) {
            axios.get('/collaborators/api/destroy', {
                params: {
                    ids: this.selectedCollaborators
                }
            })
                .then(response => {

                    // Loop through the `selectedCollaborators` that were deleted and
                    // remove them from `collaborators`
                    _.each(this.selectedCollaborators, (value, key) => {

                        console.log('Remove collaborator: ' + value);

                        // Following line produces: TypeError: Cannot read property 'collaborators' of undefined
                        this.collaborators.splice(this.collaborators.indexOf(value), 1)

                    });
                });

        }
    },

0๐Ÿ‘

What you can do is save this in a variable.

methods: {
        remove: function () {
            if (confirm('Are you sure you want to delete these collaborators?')) {
                axios.get('/collaborators/api/destroy', {
                    params: {
                        ids: this.selectedCollaborators
                    }
                })
                    .then(response => {
                        const t = this;
                        // Loop through the `selectedCollaborators` that were deleted and
                        // remove them from `collaborators`
                        _.each(this.selectedCollaborators, function (value, key) {
                            console.log('Remove collaborator: ' + value);
                            t.collaborators.splice(t.collaborators.indexOf(value), 1)
                        });
                    });

            }
        },
// [...etc...]

Leave a comment