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)文章
詳解vuex持久化插件解決瀏覽器刷新數(shù)據(jù)消失問題
這篇文章主要介紹了詳解vuex持久化插件解決瀏覽器刷新數(shù)據(jù)消失問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-04-04
VSCode寫vue項目一鍵生成.vue模版,修改定義其他模板的方法
這篇文章主要介紹了VSCode寫vue項目一鍵生成.vue模版,修改定義其他模板的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04
vue?el-date-picker?日期回顯后無法改變問題解決
這篇文章主要介紹了vue?el-date-picker?日期回顯后無法改變問題解決,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04

