1

Here is the code:

<tr v-for="(item, index) in detail" :key="item.name" class="[[ item.name ]]">
  <td>[[ index + 1 ]]</td>
  <td>[[ item.name ]]</td>

The rendered HTML looks like this:

<tr class="[[ item.name ]]">
  <td>1</td>
  <td>Job</td>
</tr>
<tr class="[[ item.name ]]">
  <td>2</td>
  <td>Jesse</td>
</tr>
<tr class="[[ item.name ]]">
  <td>3</td>
  <td>Wazert</td>
</tr>

The class="[[ item.name ]]" just don't change. What I expect is:

<tr class="Job">
  <td>1</td>
  <td>Job</td>
</tr>
<tr class="Jesse">
  <td>2</td>
  <td>Jesse</td>
</tr>
<tr class="Wazert">
  <td>3</td>
  <td>Wazert</td>
</tr>

How should I fix it?

1
  • Where did you read about using square brackets? The documentation is pretty clear and also covers how to bind data to attributes. Commented Nov 20, 2021 at 10:29

2 Answers 2

2

First thing Square bracket not worked in vue.js you need to use interpolation for binding the data dynamically.

So you need to use like For Example

HTML

<table border="1">
   <tr v-for="(item, index) in detail" :key="item.name" :class="item.name">
      <td>{{ index + 1 }}</td>
      <td>{{ item.name }}</td>
   </tr>
</table>

JS

data: function () {
  return {
    detail: [{ name: "Job" }, { name: "Jesse" }, { name: "Wazert" }],
  };
},

Here you can play with code

Sign up to request clarification or add additional context in comments.

3 Comments

thanks a lot for the codesandbox link. So if I want to change :class to :data-custom, that works too? Sorry I can't find a place to rerun the modified code on codesandbox.
no use only :class because this is built in class for binding dynamic class after modified in codesandbox press CTRL + S and check if not work then create one and paste my code there and check
thanks for the feedback, so what about data-custom? how could I do that if I don't want to use class?
1

You need to use class-binding and interpolate the data:

new Vue({
  el: "#app",
  data: () => ({ 
    detail: [ { name: "Job" }, { name: "Jesse" }, { name: "Wazert" } ] 
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <table>
    <tr v-for="(item, index) in detail" :key="item.name" :class="item.name">
      <td>{{index + 1}}</td>
      <td>{{item.name}}</td>
    </tr>
  </table>
</div>

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.