In Vue.js, you can obtain DOM elements in four ways: use ref to create a reference for a component or DOM element; obtain DOM elements based on CSS selectors through querySelector; obtain DOM element bounding rectangle information through getBoundingClientRect; Use event.target to get the DOM element that triggered the event when the event occurs.
Getting DOM in Vue
In Vue.js, there are several ways to get DOM elements, depending on the for actual needs.
1. Create a reference to the component or DOM element through the ref
ref attribute. Within a component, references can be accessed using this.$refs
. For DOM elements, you can use $refs
to access DOM nodes.
<code class="javascript">// 组件中 <template> <div ref="myDiv"></div> </template> <script> export default { mounted() { console.log(this.$refs.myDiv); // 获取 myDiv DOM 节点 } } </script> // DOM 元素 <div ref="myDiv"></div> <script> console.log(document.myDiv); // 获取 myDiv DOM 节点 </script></code>
2. Use the querySelector
##querySelector method to get DOM elements based on CSS selectors.
<code class="javascript">// 组件中 const myDiv = this.$el.querySelector('div'); // DOM 元素 const myDiv = document.querySelector('div');</code>
3. Return a DOMRect object containing the bounding rectangle information of the DOM element through the getBoundingClientRect
getBoundingClientRect method.
<code class="javascript">// 组件中 const rect = this.$el.getBoundingClientRect(); // DOM 元素 const rect = document.myDiv.getBoundingClientRect();</code>
4. Pass event.target
When an event occurs, theevent.target property contains the DOM element that triggered the event.
<code class="javascript">// 在事件处理函数中 const target = event.target;</code>
The above is the detailed content of How to get dom in vue. For more information, please follow other related articles on the PHP Chinese website!