vue中獲取標簽方法


1、HTML DOM querySelector() 方法

  按照以前jq方式, CSS 選擇器來獲取元素標簽   [在mounted方法里面執行]

  document.querySelector獲取的是被選中元素的第一個元素;

  document.querySelectorAll獲取到所有被選中元素;

  eg:document.querySelector("#demo");

    document.querySelector(".demo");

    document.querySelector("p");

    document.querySelector("a, p")

    document.querySelector("p.demo");

    document.querySelector("a[target]");

2、vue的ref和$refs方法

  ref是寫在html里面的,相當於標簽的索引,$refs 是所有注冊過的ref的一個集合,然后通過$refs找到對應的ref,然后進行操作。

  ref在dom標簽上,則$refs是dom標簽;ref在組件上,則$refs是子組件實例;

  相同的ref時,到底取得哪一個時問題,所以ref優先級也是比較重要:

  1、同一層級有相同的ref,最終通過$refs取得后面的元素(后>前);

  2、嵌套層級(父子關系)的標簽,最終通過$refs取得父親元素(父>子);

  使用方式:以下舉例說明:

  a、單純獲取當前組件的元素

    <p ref="test" id="demo">你好</p>

    在js里面用this.$refs.test就可以獲取到p標簽

    等同於:document.getElementById('demo'),但是$refs會減少獲取dom節點的消耗

  b、當獲取的元素的ref是變量

    <p :ref="test">你好</p>

    在js里面用this.$refs[this.test]就可以獲取到p標簽

  c、父組件獲取子組件的方法

  子組件

<template>
  <div>
    childComponent
  </div>
</template>
 
<script>
  export default {
    name: "child",
    methods: {
      childClick(e) {
        console.log(e)
      }
    }
  }
</script>

  父組件

<template>
  <div>
    <button @click="parentClick">點擊</button>
    <Child ref="mychild" />   //使用組件標簽
  </div>
</template>
 
<script>
  import Child from ‘./child‘;   //引入子組件Child
  export default {
    name: "parent",
    components: {
      Child    // 將組件隱射為標簽
    },
    methods: {
      parentClick() {
        this.$refs.mychild.childClick("我是子組件里面的方法哦");  // 調用子組件的方法childClick
      }
    }
  }
</script>

 

既然是取dom,操作dom,所以最好不要在模板或computed里使用!

這里是漂亮的分割線

 


 

  

 


免責聲明!

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



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