Vue.js $refs用法案例詳解
盡管有 prop 和事件,但是有時仍然需要在 JavaScript 中直接訪問子組件。為此可以使用 ref 為子組件指定一個引用 ID。
ref 為子組件指定一個引用 ID,使父組件能通過 ref 直接訪問子組件中的數(shù)據(jù)
通過 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>
到此這篇關(guān)于Vue.js $refs用法案例詳解的文章就介紹到這了,更多相關(guān)Vue.js $refs用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue.js組件vue-waterfall-easy實現(xiàn)瀑布流效果
這篇文章主要為大家詳細介紹了vue.js實現(xiàn)瀑布流之vue-waterfall-easy的相關(guān)資料,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08
Ant Design Vue如何生成動態(tài)菜單a-menu
這篇文章主要介紹了Ant Design Vue如何生成動態(tài)菜單a-menu問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
ElementUI?el-table?樹形數(shù)據(jù)的懶加載的實現(xiàn)
當面對大量數(shù)據(jù)時,一次性加載所有數(shù)據(jù)可能會導致性能問題,我們可以實現(xiàn)樹形數(shù)據(jù)的懶加載,本文主要介紹了ElementUI?el-table?樹形數(shù)據(jù)的懶加載,感興趣的可以了解一下2024-06-06
vite+ts vite.config.ts使用path報錯問題及解決
這篇文章主要介紹了vite+ts vite.config.ts使用path報錯問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10

