2016-04-18 31 views
0

我失去了vue.js的基礎知識:/我想點擊按鈕後在html中添加新列,但我無法訪問json中的特定位置。vue.js - 如何更新JSON?

<div id="app"> 
    <div class="container"> 
     <div class="row" v-for="row in json._children"> 
      <div class="col-xs-{{ col.size }}" v-for="col in row._children"> 
       <div v-for="module in col._children"> 
        {{module.moduleType}} 
       </div> 
       <button v-on:click="addModule(col, $event)">Add</button> 
      </div> 
     </div> 
    </div> 
</div> 

JS

new Vue({ 
    el: '#app', 
    data: { 
     json: { 
      'type': 'panel', 
      '_children': [ 
       { 'type': 'row', '_children': [ { 'type': 'col', 'size': '2' }, { 'type': 'col', 'size': '10', '_children': [{ 'type': 'module', 'moduleType': 'HTML' }] } ] }, 
       { 'type': 'row', '_children': [ { 'type': 'col', 'size': '5' }, { 'type': 'col', 'size': '7' } ] } 
      ] 
     } 
    }, 
    methods: { 
     addModule: function(currentColumn, e) { 
      // ???????? 
     } 
    } 
}); 

任何人可以在這方面幫助?預先感謝您

回答

0

如果您想添加一列到一行,您應該將該行傳遞給addModule()。你不應該嗎? 另外,我通過$index知道在哪個位置插入新列:

<button v-on:click="addModule(row, $index, $event)">Add</button> 

那麼所有你需要做的就是splice()新對象到該行的_children陣列。

methods: { 
    addModule: function(row, colIndex, e) { 
     var newCol = { type: 'col', size: 1 } 
     row._children.splice(colIndex, 0, newCol) 
     //or to insert to the right: 
     row._children.splice(colIndex + 1, 0, newCol) 
    } 
} 
+0

太棒了!我正是這個意思。非常感謝你! –