user1506145
user1506145

Reputation: 5296

VueJS Using Vue.set on a nested array

I know I can use Vue.set to modify a single element in an array: https://v2.vuejs.org/v2/guide/list.html#Caveats

But how can I modify a single element in a nested array or nested object/array? Perhaps it my data looks like this:

data:{
      lists:[[1,2,3],[2,3,4]],
      another_list:[[213,123, {hello:'sdf'}], 12, 123]
}

How can I edit every single element reactively?

Upvotes: 2

Views: 3512

Answers (1)

ytbryan
ytbryan

Reputation: 2694

This is for Vue.js 2.2.6.

Assuming you are using single-file component .vue, you can use this.

For example: this.lists[0][0] = 2, will change the first value of first array to 2.

Update: due to the caveat with array, we need to use slice to update arrays. Read https://v2.vuejs.org/v2/guide/list.html#Caveats

<template>
 <button v-on:click="modify"> modify </button>
</template>

<script>
export default {

    methods: {
      modify: function() {
        console.log(this.lists)
        this.lists[0].splice(2,2,3) 
        console.log(this.lists)
      }
    }, 
    
  data: function () {
      return {
          lists:[[1,2,3],[2,3,4]],
          another_list:[[213,123, {hello:'sdf'}], 12, 123]
      }
    }
}
</script>

The console output will be

[[1,2,3],[2,3,4]]
[[2,2,3],[2,3,4]]

Upvotes: 1

Related Questions