1

I've got an array in vue.js 2 with this structure:

data() {
    return {
        ports: [
            { id: 1, name: "example", "age": 10, scores: [ {index: 1, value: 100}, {index: 2, value: 200} ]},
            { id: 2, name: "example", "age": 10, scores: [ {index: 1, value: 100}, {index: 2, value: 200} ]}
            { id: 3, name: "example", "age": 10, scores: [ {index: 1, value: 100}, {index: 2, value: 200} ]}
            { id: 4, name: "example", "age": 10, scores: [ {index: 1, value: 100}, {index: 2, value: 200} ]}
        ]
    }
}

I want to replace the scores of port with id 1. I know I can replace the entire port like this:

Vue.set(this.ports, 0, newPort);

But then scores on the port object is not reactive anymore and it does not rerender in my subcomponents!

How could I accomplish this?

4
  • does changing another data after replacing scores work? Commented Sep 8, 2018 at 10:43
  • That's the problem. Right now I change the entire port and then scores is not reactive. I only need to change the scores! Commented Sep 8, 2018 at 10:46
  • i dont think it's possible for vue to detect changes in array right now, you could add another data and change that every time you replace something in the array. Commented Sep 8, 2018 at 10:48
  • Hmm how would that look like? Commented Sep 8, 2018 at 10:50

1 Answer 1

4

But then scores on the port object is not reactive anymore and it does not rerender in my subcomponents!

The scores property will be reactive provided that it exists on the newPort object at the time of the Vue.set call.

I want to replace the scores of port with id 1.

Why are you replacing the entire port object instead of just the scores? This will work:

this.ports.find(port => port.id === 1).scores = newScores
Sign up to request clarification or add additional context in comments.

Comments

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.