2

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?

3
  • why don't you use methods object and loop through your array elements? Commented Apr 5, 2017 at 13:02
  • 1
    I'm afraid I don't understand what you mean... Commented Apr 5, 2017 at 13:19
  • For example modify the first nested element of lists: Vue.set('lists[0][0]', 2); Commented Apr 5, 2017 at 14:19

1 Answer 1

1

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]]
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks! Will the reactivity work as well? For instance if I have {list[0][0]}, will it rerender?
I think you forgot the s instead of method it needs to be methods
Thanks for pointing out Amr. Yes, the reactivity will work.
@user1506145 It seems that array does not get updated and will not rerender. This is weird because it works for other types like string. Will update you if I find something.
Asked the question here stackoverflow.com/questions/43243637/… @user1506145
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.