2017-07-12 121 views
2

我的組件VUE這樣的:如何替換vue.js 2中的元素?

<template> 
    <div> 
     <ul class="list-inline list-photo"> 
      <template v-for="item in items"> 
       <li> 
        <a href="javascript:;" class="thumbnail thumbnail-upload" 
         :title="trans('store.add.img.button')" @click="addPhoto"> 
         <span class="fa fa-plus fa-2x"></span> 
        </a> 
       </li> 
      </template> 
     </ul> 
    </div> 
</template> 
<script> 
    export default { 
     data() { 
      return { 
       items: [1, 2, 3, 4, 5] 
      } 
     }, 
     methods: { 
      addPhoto() { 
       // change element clicked 
      } 
     } 
    } 
</script> 

如果在標籤裏的鏈接點擊,我想替換元素裏是這樣的:

<li> 
    <div class="thumbnail"> 
     <img src="https://myshop.co.id/img/no-image.jpg" alt=""> 
     <a href="javascript:;" class="thumbnail-check"><span class="fa fa-check-circle"></span></a> 
    </div> 
</li> 

所以,如果我點擊第二個元素裏,它將取代seconde元素li

我該怎麼辦?

回答

1

只需使用v-if/v-else切換的元素,跟蹤的點擊者的物體或類似

export default { 
    data() { 
     return { 
      items: [1, 2, 3, 4, 5], 
      clicked: [] // using an array because your items are numeric 
     } 
    }, 
    methods: { 
     addPhoto(item) { 
      this.$set(this.clicked, item, true) 
     } 
    } 
} 

,並在您的模板

<li v-for="item in items"> 
    <div class="thumbnail" v-if="clicked[item]"> 
     <img src="https://myshop.co.id/img/no-image.jpg" alt=""> 
     <a href="javascript:;" class="thumbnail-check"><span class="fa fa-check-circle"></span></a> 
    </div> 
    <a v-else href="javascript:;" class="thumbnail thumbnail-upload" 
     :title="trans('store.add.img.button')" @click="addPhoto(item)"> 
     <span class="fa fa-plus fa-2x"></span> 
    </a> 
</li> 

演示〜https://jsfiddle.net/49gptnad/392/

+1

我很確定'Set'沒有反應。 –

+0

@DecadeMoon是的,只是發現,而試圖創建一個演示 – Phil

+0

@DecadeMoon固定使用普通對象 – Phil