文章目录[隐藏]
尽管有 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>
到此这篇关于Vue.js $refs用法案例详解的文章就介绍到这了,更多相关Vue.js $refs用法内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!
您可能感兴趣的文章:
- setup+ref+reactive实现vue3响应式功能
- Vue之ref属性详解
- Vue3中的Refs和Ref详情
- Vue3中reactive函数toRef函数ref函数简介
- Vue3.0中Ref与Reactive的区别示例详析
- Vue3中ref与reactive的详解与扩展
- Vue3中ref与toRef的区别浅析
- vue3组合API中setup、 ref、reactive的使用大全
- Vue中ref的用法及演示
本文由 华域联盟 原创撰写:华域联盟 » Vue.js $refs用法案例详解
转载请保留出处和原文链接:https://www.cnhackhy.com/81508.htm