Vue.js $refs用法案例詳解
阿新 • • 發佈:2021-09-14
儘管有 prop 和事件,但是有時仍然需要在 中直接訪問子元件。為此可以使用 ref 為子元件指定一個引用 ID。
ref 為子元件指定一個引用 ID,使父元件能通過 ref 直接訪問子元件中的資料
通過 this.$refs.outsideComponentRef 能直接定位到 ref=“outsideComponentRef” 的上,並返回該例項化物件
一、ref使用在外面的元件上
<div id="app"> <component-father ref="outsideComponentRef"></component-father> </div> <script> var refoutsidehttp://www.cppcns.comcomponentTem = { template: "<div class='childComp'><h5>{{test}}</h5></div>",data(){ return{ test:'我是子元件' } } }; new ({ 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 = { templkBoXereOQate: "<div class='childComp'><h5>{{test}}</h5></div>",data(){ return{ test:'我是子元件' } } }; new Vue({ el: "#app",components: { kBoXereOQ"component-father": refoutsidecomponentTem },mounted:function () { console.log(this.$refs.outsideComponentRef); // 返回 “<p>p標籤</p>”物件 } }); </script>
到此這篇關於Vue. $refs用法案例詳解的文章就介紹到這了,更多相關Vue.js $refs用法內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!