Vue:根据自己的src属性显示/隐藏图片

时间:2019-08-05 15:51:54

标签: javascript vue.js vuejs2

是否可以在vue模板中引用当前元素?我尝试使用this,但这似乎不起作用。

基本上,我只想显示img标记,如果source属性的长度大于零,则该长度随其所在的引导程序下拉列表的选择而改变。

<img id="active_item_icon" v-show="this.src.length > 0 || !!data.icon_url" :src="data.icon_url" alt="Item Icon">

完整代码:

<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" style="width:100%;text-align:left;" type="button" id="dropdown-item-icon-url" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    <!-- This is the image that I want to watch -->
    <img id="active_item_icon" v-show="this.src.length > 0 || !!data.icon_url" :src="data.icon_url" alt="Item Icon">
    <span v-show="!data.icon_url">No Icon Selected</span>
  </button>
  <ul class="dropdown-menu" style="width:100%" aria-labelledby="dropdown-item-icon-url">
    <li v-on:click="updateURL" v-for="item in $store.state.icons" :key="item.id">
      <a href="#"><img :src="$store.getters.icon(item.id)" alt=""></a>
    </li>
  </ul>
  <input type="hidden" name="icon_url" id="item_icon_url" :value="data.icon_url || ''">
</div>

2 个答案:

答案 0 :(得分:0)

如果您可以访问data.icon_url作为img标签源,并且它是一个字符串,则可以对此进行v-if操作,然后删除or。

<img id="active_item_icon" v-show="data.icon_url.length > 0" :src="data.icon_url" alt="Item Icon">

答案 1 :(得分:0)

不确定为什么我没有想到这一点,但是我只需要将其绑定到某些数据即可:

export default {
  data: () => ({
    showUrl: ''
  }),
  methods: {
    updateURL(e) {
      this.showUrl = e.currentTarget.querySelector('img').src
    },
  }
}
<img id="active_item_icon" v-show="!!showUrl.length" :src="showUrl" alt="Item Icon">