简体   繁体   中英

How to get img and p tag inside div using vue?

I want to get image src and text of <p> when I click on <div> element.

<div class="image-holder" @click="showImage($event)" >
  img class="img-fluid"  src="images/models-detail-small.png" alt="" />
  <p>elevation {{elevationA}}- {{elevationASqt}} sq. ft</p>
</div>


var vm = new Vue({
    el: '#app',
    methods: {
        showImage: function (event) {
            element = event.currentTarget;
            console.log(element);

            // href = element.getAttribute('src');
            // this.imgSrc=href;
        }
    }
});

You should add extra wrapper for hidden elements to toggle visibility

 new Vue({ el: "#app", data: () => ({ imageVisible: false, imgSrc: '', text: '' }), methods: { setData() { this.imageVisible = true this.imgSrc = 'https://picsum.photos/200/300' this.text = 'Lorem ipsum dolor' } } })
 .image-holder { width: 200px; min-height: 300px; background: #ccc; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div class="image-holder" @click="setData()"> <div v-if="imageVisible"> <img class="img-fluid" :src="imgSrc" alt="" /> <p>{{ text }}</p> </div> </div> </div>

Considering you are getting the div element by event.CurrentTarget You can try something like below.

var vm = new Vue({
    el: '#app',
    methods: {
        showImage: function (event) {
            element = event.currentTarget;
            console.log(element);
            var img = element.getElementsByTagName('img');
            this.imgSrc = img.length > 0 ? img[0].src : null;
            var pTag = element.getElementsByTagName('p');
            this.text = pTag.length > 0 ? pTag[0].textContent : null;
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM