vue.js父子组件通信动态绑定

本文通过一个简单的示例介绍了Vue.js中如何实现父子组件之间的数据传递与双向绑定。父组件通过props向子组件传递数据,并展示了如何使用v-model实现输入框值的双向绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id='app'>
    <!--这里的作用是将父组件渲染到页面上-->
    <father></father>
</div>
</body>
<script src="https://cdn.bootcss.com/vue/2.3.4/vue.js"></script>
<script type="text/x-template" id="father">
    <div>
        <!--这里实现一个双向绑定-->
        <!--parentMsg变量必须在data中声明,不然会报错,我就错在这个坑-->
        <input v-model="parentMsg">
        <br>
        <child :my-message="parentMsg"></child>
    </div>
</script>
<script type="text/x-template" id="child">
    <div> {{'父组件传递的数据为:'+ myMessage }} </div>
</script>
<script>

    Vue.component('father',{
//        这里我直接把template写到前面script标签中了,写在这里一大坨,难看
        template:'#father',
        data:function(){
            return {
                parentMsg:''
            }
        }
    });

    //在 Vue 中,父子组件的关系可以总结为 props down, events up。
    // 父组件通过 props 向下传递数据给子组件,子组件通过 events 给父组件发送消息
    Vue.component('child', {
        props: ['myMessage'],//这里的props选项是用来实现父子组件的通信的,传递下来的消息字组件用花括号接住
        template: '#child'
    });

    new Vue({
        el:'#app'
    })

</script>
</html>

转载于:https://www.cnblogs.com/lantinggumo/p/7636723.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值