Vue獲取DOM節點
1、原生js獲取節點的方式
-
document.getElementById() -- 使用id獲取方式較少
-
document.getElementByClassName() -- 類名
-
document.getElementByTagName() -- 標簽名
-
document.getElementByName() -- name屬性,使用少
-
document.querySelector() -- css選擇符模式,返回該模式匹配的第一個元素,
結果為一個元素
;沒有匹配元素時,返回值為nullfunction funb() { var selectDiv = document.querySelector("#list li:nth-child(3)"); selectDiv.style.color = "red"; // console.log(selectDiv) } funb()
-
document.querySelectorAll() -- css選擇模式,返回該模式匹配的所有元素,
結果為一個數組
function func() { var selectDiv = document.querySelectorAll(".text ul>li"); selectDiv[0].style.color = "red"; //打印出為NodeList對象 -- 是節點的集合,可以使用 Array.from() 將其轉換為數組 console.log(selectDiv) } func()
2、在vue項目中引入jquery
jQuery中包裹后的DOM對象實際上是一個數組,要獲得純粹的DOM對象可以有兩種方式:
-
使用數組索引方式訪問,例如:
var dom = $(dom)[0];
如: $("#id")[0] -
使用函數get()訪問,例如:
var dom = $(dom).get(0);
get()函數中的參數為索引號
3、ref屬性
-
此屬性是獲取dom對象,作用:與id作用相似,相當於給標簽起了一個類似於id。
-
-
操作一個元素時,在元素上添加ref屬性,之后使用$refs來獲取該元素,之后進行操作
this.$refs.ref值
<template> <div> <div class="contaier" ref="box" style="width: 100px;height: 100px;"> 測試元素的ref屬性 </div> <button type="button" @click="showRef()">點擊</button> </div> </template> <script> export default { methods: { showRef() { this.$refs.box.style.color = "red"; console.log(this.$refs.box); //獲取到元素本身 -- <div class="contaier" ref="box" style="width: 100px;height: 100px;">測試元素的ref屬性</div> console.log(this.$refs.box.style); //獲取到元素的樣式 } } //this.$refs即為搜索所有的ref的一個對象,this.$ref可以訪問到vue實例中的所有設置ref屬性的DOM元素,並對其操作 //組件中的子組件的ref指向的時組件的實例 } </script>
4、直接使用DOM API尋找元素
<script> //這種方法足夠簡單直觀,Vue組件在patch階段結束時會把this.$el賦值為掛載的根dom元素,我們可以直接使用$el的querySelector, querySelectorAll等方法獲取匹配的元素。 ... mounted () { let elm = this.$el.querySelector('#id') } </script>