vue中怎么實現獲取當前點擊對象this


應用場景

在評論列表中,有很多條評論(通過循環出來的評論列表),評論的文字有多跟少,默認展示2行超出顯示點擊查看更多,,要點擊查看更多對當前的這條評論進行全部評論展示!

問題描述

要是在傳統的點擊事件中,我們可以獲取當前點擊事件的this來執行相應的操作,但是在vue中沒有這個點擊this事件!

解決問題

1、在vue中我們要通過組件的方式來實現對當前元素進去切換

父組件

<v-content :cont="item.content"></v-content>

子組件content

<template>
    <div>
    <p class="q-des-c" :class="{'text-overflow':flowshow}">{{cont}}</p>
    <p class="ckqw" @click="allText" :style="{'display':showHide}">{{kan}}</p>
    </div>
</template>
<script>
    export default {
        data(){
            return{
                flowshow:true,
                kan:"查看全文",
                showHide:"block"
                
            }
        },
        methods: {
            allText:function(){
                if(this.flowshow){
                    this.flowshow=false;
                    this.kan="收起"
                }else{
                    this.flowshow=true;
                    this.kan="查看全文"
                }
            },
        },
        props: {
            cont:{
                type:String,
                default:''
            },
        },
        created(){
//            console.log("字數"+this.cont.length);
            if(this.cont.length>36){
                this.showHide="block";
            }else{
                this.showHide="none";
            }
        }
    }
</script>

2、借助事件對象event來獲取相關值進行操作

<button @click = “clickfun(2,$event)”>點擊</button>

methods

$event 的用法--獲取當前父元素,子元素,兄弟元素

methods: {
clickfun(other,e) {
// e.target 是你當前點擊的元素
// e.currentTarget 是你綁定事件的元素
    #獲得點擊元素的前一個元素
    e.currentTarget.previousElementSibling.innerHTML
    #獲得點擊元素的第一個子元素
    e.currentTarget.firstElementChild
    # 獲得點擊元素的下一個元素
    e.currentTarget.nextElementSibling
    # 獲得點擊元素中id為string的元素
    e.currentTarget.getElementById("string")
    # 獲得點擊元素的string屬性
    e.currentTarget.getAttributeNode('string')
    # 獲得點擊元素的父級元素
    e.currentTarget.parentElement
    # 獲得點擊元素的前一個元素的第一個子元素的HTML值
    e.currentTarget.previousElementSibling.firstElementChild.innerHTML
  
    }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM