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>

posted @ 2022-07-20 18:16  猫老板的豆  阅读(71)  评论(0编辑  收藏  举报