vue $refs

Vue中使用$refs引用子组件
本文介绍Vue中如何利用$refs特性访问子组件和DOM元素,通过示例展示了如何在父组件中引用并操作子组件实例。

官方地址:vm.$refs

<!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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安果移不动

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值