Vue


ref 获取 DOM

<p><strong>ref 用在 html 标签上</strong></p> <pre><code class="language-javascript">&amp;lt;template&amp;gt; &amp;lt;p ref=&amp;quot;andy&amp;quot;&amp;gt;Andy&amp;lt;/p&amp;gt; &amp;lt;/template&amp;gt; &amp;lt;script setup&amp;gt; import { ref, onMounted } from &amp;quot;vue&amp;quot;; let andy = ref(null) console.log(&amp;quot;aaa&amp;quot;) onMounted(()=&amp;gt;{   console.log(andy.value.innerText) // 在 setup 执行时,template 的元素还没挂载到页面上,所以要在 onMounted 才能获取到元素 }) console.log(&amp;quot;bbb&amp;quot;) &amp;lt;/script&amp;gt;</code></pre> <pre><code class="language-javascript">// 结果: // aaa // bbb // Andy</code></pre> <hr /> <p><strong>ref 用在 组件 标签上</strong> 获取的就是组件实例对象</p> <pre><code class="language-javascript">&amp;lt;template&amp;gt; &amp;lt;Child ref=&amp;quot;child&amp;quot; /&amp;gt; &amp;lt;button @click=&amp;quot;getChildRef&amp;quot;&amp;gt;获取Child的ref&amp;lt;/button&amp;gt; &amp;lt;/template&amp;gt; &amp;lt;script setup&amp;gt; import { ref } from &amp;quot;vue&amp;quot; import Child from &amp;quot;./Child.vue&amp;quot;; let child = ref() function getChildRef() { console.log(child.value.age) } &amp;lt;/script&amp;gt;</code></pre> <pre><code class="language-javascript">&amp;lt;template&amp;gt; 我是Child &amp;lt;/template&amp;gt; &amp;lt;script setup&amp;gt; import { ref, defineExpose } from &amp;quot;vue&amp;quot; let name = ref('Child') let age = ref(24) defineExpose({ name, age }) &amp;lt;/script&amp;gt;</code></pre> <hr /> <p><strong>ref 与 document.getElementById() 的区别</strong> 不同vue文件的ref可以同名,id不可以,因为是单页面应用</p>

页面列表

ITEM_HTML