inherithandle
inherithandle

Reputation: 2664

cannot update the property of vue object inside axios success callback

I have axios callback and I want to update the property of vue object and I have 2 way binding between the input tag and the edited property so that text box is hidden or displayed depending the edited property. when I update edited property to false inside callback, the textbox won't be hidden. but textbox is hidden or displayed when I updated outside axios callback.

editBtnClicked: function (index) {
    var promise = null;

    axios.put('/rest/project', this.projects[this.currentIndex]).then(response => {
        // textbox won't be hidden or displayed even if this statement is executed.
        this.projects[this.currentIndex].edited = !(this.projects[this.currentIndex].edited);
    });

    // textbox is hidden or displayed when this statement is excuted.
    // this.projects[this.currentIndex].edited = !(this.projects[this.currentIndex].edited);
}

Could anyone tell me why? and you can check the full code: https://gist.github.com/inherithandle/e61a5ab2809581a5d36de08b4e4349f1

Upvotes: 1

Views: 288

Answers (2)

Andrew Li
Andrew Li

Reputation: 1055

My opinion is that is caused by the property edited of project item in projects array is added to the project dynamically.
Adding property to Ojbect

When adding the property to Object, you have to use $set.

Due to the limitations of modern JavaScript (and the abandonment of Object.observe), Vue cannot detect property addition or deletion. However, it’s possible to add reactive properties to a nested object using the Vue.set(object, key, value) method:

Please try the below code in line 181 and other lines that changes edited of project item in your source code of github.

this.$set(this.projects[this.currentIndex], 'edited', false);

Upvotes: 2

lei li
lei li

Reputation: 1342

Your currentIndex always be 0, and your two if statements will always return false.

Upvotes: 0

Related Questions