Skip to content
Advertisement

How does vue watch sublist change or v-model

I try to watch a list that has sub list and some <input> can change the sublist well.

<div id="app">
    <div v-for="sub in list">
        <div v-for="(v,idx) in sub">
            <input v-model="sub[idx]"/>
        </div>
    </div>
</div>
<script>
new Vue({
    el: "#app",
    data: {
        list: [['one','two']]    
    },
    watch: {
        list: funtion(){
            console.log('change')
        }
    }
})
</script>

when I modify the input,watcher doesn’t work

Advertisement

Answer

Do a deep watch in order to watch nested changes and trigger the watch:

watch: {
   list: {
     handler() {
         console.log('change')
     },
     deep: true
   }
}

Interesting:

If the nested data is any of the following, the watch will not fire without a deep watch:

  • array of objects (by far the most common)
  • object of objects
  • object of arrays

But if the nested data is an array of arrays, as in your code, Vue can detect it. It would have worked with the typo fixed (as addressed in @BorisK’s answer below).

This is somewhat unexpected because we think of Vue as unable to detect deep changes without a deep watch, but it can with an array of arrays, and not just in the template.

Demo

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement