淺談Vue.js中ref ($refs)用法舉例總結(jié)
更新時間:2017年12月19日 09:25:07 作者:該帳號已被查封
本篇文章主要介紹了淺談Vue.js中ref ($refs)用法舉例總結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
本文介紹了Vue.js中ref ($refs)用法舉例總結(jié),分享給大家,具體如下:
看Vue.js文檔中的ref部分,自己總結(jié)了下ref的使用方法以便后面查閱。
一、ref使用在外面的組件上
HTML 部分
<div id="ref-outside-component" v-on:click="consoleRef"> <component-father ref="outsideComponentRef"> </component-father> <p>ref在外面的組件上</p> </div>
js部分
var refoutsidecomponentTem={
template:"<div class='childComp'><h5>我是子組件</h5></div>"
};
var refoutsidecomponent=new Vue({
el:"#ref-outside-component",
components:{
"component-father":refoutsidecomponentTem
},
methods:{
consoleRef:function () {
console.log(this); // #ref-outside-component vue實例
console.log(this.$refs.outsideComponentRef); // div.childComp vue實例
}
}
});
二、ref使用在外面的元素上
HTML部分
<!--ref在外面的元素上--> <div id="ref-outside-dom" v-on:click="consoleRef" > <component-father> </component-father> <p ref="outsideDomRef">ref在外面的元素上</p> </div>
JS部分
var refoutsidedomTem={
template:"<div class='childComp'><h5>我是子組件</h5></div>"
};
var refoutsidedom=new Vue({
el:"#ref-outside-dom",
components:{
"component-father":refoutsidedomTem
},
methods:{
consoleRef:function () {
console.log(this); // #ref-outside-dom vue實例
console.log(this.$refs.outsideDomRef); // <p> ref在外面的元素上</p>
}
}
});
三、ref使用在里面的元素上---局部注冊組件
HTML部分
<!--ref在里面的元素上--> <div id="ref-inside-dom"> <component-father> </component-father> <p>ref在里面的元素上</p> </div>
JS部分
var refinsidedomTem={
template:"<div class='childComp' v-on:click='consoleRef'>" +
"<h5 ref='insideDomRef'>我是子組件</h5>" +
"</div>",
methods:{
consoleRef:function () {
console.log(this); // div.childComp vue實例
console.log(this.$refs.insideDomRef); // <h5 >我是子組件</h5>
}
}
};
var refinsidedom=new Vue({
el:"#ref-inside-dom",
components:{
"component-father":refinsidedomTem
}
});
四、ref使用在里面的元素上---全局注冊組件
HTML部分
<!--ref在里面的元素上--全局注冊--> <div id="ref-inside-dom-all"> <ref-inside-dom-quanjv></ref-inside-dom-quanjv> </div>
JS部分
Vue.component("ref-inside-dom-quanjv",{
template:"<div class='insideFather'> " +
"<input type='text' ref='insideDomRefAll' v-on:input='showinsideDomRef'>" +
" <p>ref在里面的元素上--全局注冊 </p> " +
"</div>",
methods:{
showinsideDomRef:function () {
console.log(this); //這里的this其實還是div.insideFather
console.log(this.$refs.insideDomRefAll); // <input type="text">
}
}
});
var refinsidedomall=new Vue({
el:"#ref-inside-dom-all"
});
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue中改變選中當前項的顯示隱藏或者狀態(tài)的實現(xiàn)方法
下面小編就為大家分享一篇vue中改變選中當前項的顯示隱藏或者狀態(tài)的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02
探秘Vue異步更新機制中nextTick的原理與實現(xiàn)
nextTick?是?Vue?提供的一個重要工具,它的作用主要體現(xiàn)在幫助我們更好地處理異步操作,下面就跟隨小編一起來探索一下nextTick的原理與實現(xiàn)吧2024-02-02

