0

Stuck on what is most likely just a syntax issue. I want to replace the '1' in 'play1' with the v-for index.

<tr v-for="index in 5">
  <td>{{player1.round1.play1}}</td>
  <td>{{player2.round1.play1}}</td>
</tr>

I tried many variations of {{player1.round1.play + index}} with no success.

1 Answer 1

2
<tr v-for="index in 5">
  <td>{{player1.round1['play'+index]}}</td>
  <td>{{player2.round1['play'+index]}}</td>
</tr>

within the double-curlies of the vue template, the content is handled as javascript.

when looking up an object in javascript you can either pass the key using the dot notation or the bracket syntax.

For example, if you have an object such as this:

const objectA = {
  objectB: {
    objectC: {
    }
  }
};

you can look up objectC either using dot notation:
objectA.objectB.objectC

or using brackets:
objectA['objectB']['objectC']

note that when you are using brackets, that you have to use a simple type, a number or a string (technically symbols are also accepted, but let's not worry about that right now). The bracket syntax does however allow you to use a variable in order to access an object, like so:

let b='objectB';
let c='C';
objectA[b]['object' + c];
objectA[b][`object${c}`];

knowing this, you can then use that to access the right object inside your vue template like this:

<td>{{player1.round1['play'+index]}}</td>

or, using template literals:

<td>{{player2.round1[`play${index}`]}}</td>
Sign up to request clarification or add additional context in comments.

2 Comments

While this will probably solve the problem, can you explain WHY it works the way it does? Also, the backtick strings aren't really necessary here :/
correct, I removed the template literals, but added example using them properly

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.