旁观自己 善待朝夕|

猫老板的豆

园龄:9年4个月粉丝:52关注:0

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 中国大陆许可协议进行许可。

posted @   猫老板的豆  阅读(74)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.