Vue 通過ref獲取DOM元素
ref
被用來給元素或子組件注冊引用信息。引用信息將會注冊在父組件的 $refs
對象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子組件上,引用就指向組件實例:
<!-- `vm.$refs.p` will be the DOM node -->
<p ref="p">hello</p>
<!-- `vm.$refs.child` will be the child component instance -->
<child-component ref="child"></child-component>
<!--。。。。。-->
methods: {
myclick() {
console.log(this.$refs.p.innerText);
}
}
當 v-for
用於元素或組件的時候,引用信息將是包含 DOM 節點或組件實例的數組。通過this,$refs.引用 即可獲取DOM或子組件,此時可以獲取子組件的data或methods
關於 ref 注冊時間的重要說明:因為 ref 本身是作為渲染結果被創建的,在初始渲染的時候你不能訪問它們 - 它們還不存在!$refs
也不是響應式的,因此你不應該試圖用它在模板中做數據綁定。