vue $refs

版权声明:独学而无友,则孤陋寡闻。q群582951247 https://blog.csdn.net/mp624183768/article/details/88122089

官方地址:vm.$refs

  • 类型Object

  • 只读

  • 详细

    一个对象,持有注册过 ref 特性 的所有 DOM 元素和组件实例。

  • 参考

  • 案例
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.2.0/normalize.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
    <title>Title</title>
    <style>
        #app {
            margin: 1em;
            font-size: 1.2em;
        }
        .component div {
            margin-bottom: 1em;
        }
    </style>
</head>
<body>
<div id="app">
    <my-component ref="com1" :parent-msg="msg"></my-component>
    <my-component2 ref="com2"></my-component2>
    <my-component3 ref="com3"></my-component3>
    <hr>
    <div>{{msg}}</div>
</div>
<script type="text/x-template" id="my-component">
    <div class="component">
        <div> ParentMsg: {{ parentMsg }} </div>
        <div> ChildMsg: {{ msg }} </div>
    </div>
</script>
<script>
    Vue.component('my-component2', {
        template: '<div>{{ msg }}</div>',
        data() {
            return {
                msg: 'Hi COMP2'
            }
        }
    });
    Vue.component('my-component3', {
        template: '<div>{{ msg }}</div>',
        data() {
            return {
                msg: 'Hi COMP3'
            }
        }
    });
    //register
    Vue.component('my-component',{
        props:['parentMsg'],
        template:'#my-component',
        mounted(){
            console.log("$parent:",this.$parent.msg);
            window.setTimeout(()=>{
                this.$parent.msg='Hello!';
            },3000);
        },
        data:function () {
            return{
                msg:'Msg of Child!'
            }
        }
    });
    // a root instance
    new Vue({
        el:"#app",
        data:{
            msg:'Msg of Parent!'
        },
        mounted(){
            console.log('$children1:',this.$refs.com1.msg);
            console.log('$children2:',this.$refs.com2.msg);
            console.log('$children3:',this.$refs.com3.msg);
        }
    });

</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/88122089