ref 获取 DOM
<p><strong>ref 用在 html 标签上</strong></p>
<pre><code class="language-javascript">&lt;template&gt;
&lt;p ref=&quot;andy&quot;&gt;Andy&lt;/p&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref, onMounted } from &quot;vue&quot;;
let andy = ref(null)
console.log(&quot;aaa&quot;)
onMounted(()=&gt;{
console.log(andy.value.innerText) // 在 setup 执行时,template 的元素还没挂载到页面上,所以要在 onMounted 才能获取到元素
})
console.log(&quot;bbb&quot;)
&lt;/script&gt;</code></pre>
<pre><code class="language-javascript">// 结果:
// aaa
// bbb
// Andy</code></pre>
<hr />
<p><strong>ref 用在 组件 标签上</strong>
获取的就是组件实例对象</p>
<pre><code class="language-javascript">&lt;template&gt;
&lt;Child ref=&quot;child&quot; /&gt;
&lt;button @click=&quot;getChildRef&quot;&gt;获取Child的ref&lt;/button&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref } from &quot;vue&quot;
import Child from &quot;./Child.vue&quot;;
let child = ref()
function getChildRef() {
console.log(child.value.age)
}
&lt;/script&gt;</code></pre>
<pre><code class="language-javascript">&lt;template&gt;
我是Child
&lt;/template&gt;
&lt;script setup&gt;
import { ref, defineExpose } from &quot;vue&quot;
let name = ref('Child')
let age = ref(24)
defineExpose({ name, age })
&lt;/script&gt;</code></pre>
<hr />
<p><strong>ref 与 document.getElementById() 的区别</strong>
不同vue文件的ref可以同名,id不可以,因为是单页面应用</p>
<hr />
<p><strong>绑定事件</strong></p>
<pre><code class="language-javascript">&lt;template&gt;
&lt;div class=&quot;container&quot; ref=&quot;container&quot;&gt;
&lt;/div&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref, computed, onMounted } from 'vue'
let container = ref(null)
onMounted(() =&gt; {
container.value.addEventListener('mousemove', mousemoveHandler)
})
function mousemoveHandler() {
console.log('mousemove')
}
&lt;/script&gt;
&lt;style&gt;
.container {
width: 200px;
height: 200px;
background-color: aqua;
}
&lt;/style&gt;</code></pre>
<hr />
<p><strong>获取 el-table DOM </strong></p>
<pre><code class="language-javascript">this.$refs.eltable.$el.querySelector('.el-table__header-wrapper th:nth-child(2)').getBoundingClientRect().left</code></pre>