华域联盟 JAVA Vue.js $refs用法案例详解

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>

到此这篇关于Vue.js $refs用法案例详解的文章就介绍到这了,更多相关Vue.js $refs用法内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » Vue.js $refs用法案例详解

转载请保留出处和原文链接:https://www.cnhackhy.com/81508.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部