Vue.js $refs用法案例詳解
更新時間:2021年09月14日 10:09:10 作者:貓老板的豆
這篇文章主要介紹了Vue.js $refs用法案例詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下
盡管有 prop 和事件,但是有時仍然需要在 JavaScript 中直接訪問子組件。為此可以使用 ref 為子組件指定一個引用 ID。
ref 為子組件指定一個引用 ID,使父組件能通過 ref 直接訪問子組件中的數據
通過 this.$refs.outsideComponentRef 能直接定位到 ref=“outsideComponentRef” 的上,并返回該實例化對象
一、ref使用在外面的組件上
<div id="app"> <component-father ref="outsideComponentRef"></component-father> </div> <script> var refoutsidecomponentTem = { template: "<div class='childComp'><h5>{{test}}</h5></div>", data(){ return{ test:'我是子組件' } } }; new Vue({ el: "#app", components: { "component-father": refoutsidecomponentTem }, mounted:function () { console.log(this); // #app vue實例 console.log(this.$refs.outsideComponentRef); // VueComponent vue實例 console.log(this.$refs.outsideComponentRef.test); // '我是子組件' } }); </script>
二、ref使用在外面的元素上
<div id="app"> <component-father></component-father> <p ref="outsideComponentRef">p標簽</p> </div> <script> var refoutsidecomponentTem = { template: "<div class='childComp'><h5>{{test}}</h5></div>", data(){ return{ test:'我是子組件' } } }; new Vue({ el: "#app", components: { "component-father": refoutsidecomponentTem }, mounted:function () { console.log(this.$refs.outsideComponentRef); // 返回 “<p>p標簽</p>”對象 } }); </script>
到此這篇關于Vue.js $refs用法案例詳解的文章就介紹到這了,更多相關Vue.js $refs用法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
VSCode寫vue項目一鍵生成.vue模版,修改定義其他模板的方法
這篇文章主要介紹了VSCode寫vue項目一鍵生成.vue模版,修改定義其他模板的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04vue?el-date-picker?日期回顯后無法改變問題解決
這篇文章主要介紹了vue?el-date-picker?日期回顯后無法改變問題解決,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04