天天看点

Vue.js之$refs

尽管有 prop 和事件,但是有时仍然需要在 JavaScript 中直接访问子组件。为此可以使用 ref 为子组件指定一个引用 ID。

一、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>