Skip to content
Advertisement

Vue JS in HTML Not Recognizing Added Objects and Properties

I have a Vue instance called myApp. I have a method in my Vue JS instance that is called loadPlannedAlerts, which is called during mounted. It’s an AJAX call that first gets JSON data, then adds to it afterwards. The data is a JSON object with key value pairs, that looks something along the lines of {key: 'value, key2: 'value2}'.

loadPlannedAlerts: function() {
        $.ajax({
            method: 'GET',
            url: '/get-my-data',
            success: function(data) {
                myApp.messages = JSON.parse(data);
                for (var i = 0; i < myApp.messages.length; i++) {
                    myApp.messages[i].findUser = '';
                }
            }
        });
}

In my HTML, I have a v-for loop that displays this message data.

<div v-for="(message, index) in messages">
    <input type="text" name="user" v-model="message.findUser">
</div>

For some reason, I can pull up the added findUser key-value in my browser’s console, and I can even see it in my browser’s dev tools Vue plugin. But The data that is typed into my message box is not binding to each of the findUsers.

Is there something I’m missing, or an order of operations that I am overlooking? Anything else that already existed in the data before I added it is binding fine.

UPDATE

If I follow Decade Moon’s solution for a regular key-value pair, where I don’t mutate the component at all, and finish building what it should look like, then assign value to it, then it works fine. If I try to assign a key-value pair where the value is another object with key-value pairs in it, then it still does not work.

Advertisement

Answer

Is myApp.messages declared upfront in the data object for that component?

It looks like you’re adding a new findUser property to each message. Vue can’t detect this (see Change Detection Caveats). You should mutate the payload before you assign it to the component (at which point Vue will make it reactive).

success: function(data) {
  const messages = JSON.parse(data);
  
  for (var i = 0; i < messages.length; i++) {
    messages[i].findUser = '';
  }

  // Do this last
  myApp.messages = messages;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement