user7531085
user7531085

Reputation:

Binding Styles in Vue.js

New to Vue.js 2. I am trying to give each div their own unique style in a v-for loop. What am I doing wrong? What is a better way to accomplish what i'm trying to do?

var tables = new Vue({
  el: '#table',
  data: {
    tables: [
   {name: 'iPhone', left:1, top:0},
      {name: 'Mac', left:150, top:0}
   ]
  }
})
.table-div
{
  width:100px;
  height: 100px;
  border:1px solid black;
  position: absolute;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div id="table">
    <div v-for="table in tables">
      <div class="table-div" v-bind:style="{top: table.top, left: table.left}">{{table.name}}</div>
    </div>
  </div>
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</body>
</html>

Upvotes: 1

Views: 1452

Answers (1)

choasia
choasia

Reputation: 10852

I think you just forgot to add 'px'. See demo below.

var tables = new Vue({
  el: '#table',
  data: {
    tables: [
   {name: 'iPhone', left:1, top:0},
      {name: 'Mac', left:150, top:0}
   ]
  }
})
.table-div
{
  width:100px;
  height: 100px;
  border:1px solid black;
  position: absolute;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div id="table">
    <div v-for="table in tables">
      <div class="table-div" v-bind:style="{top: table.top + 'px', left: table.left + 'px'}">{{table.name}}</div>
    </div>
  </div>
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</body>
</html>

Upvotes: 1

Related Questions