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>
本文作者:猫老板的豆
本文链接:https://www.cnblogs.com/bingcola/p/16499268.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步