Vue中组件之间的通信

父组件与子组件之间的参数传递
(1)父传子

<body>
<div id="app">
    <parent></parent>
</div>
<script src="../js/vue.min.js"></script>
<script>
    Vue.component("parent",{
        data:function () {
            return{ tips:'张无忌'}
        },
        template:`
            <div>
                <h4>父组件</h4>
                <form action="#"><child :myValue="tips"></child></form>
            </div>
        `
    });
    Vue.component("child",{
        template:`<input type="text" v-bind:placeholder="myValue">`,
        props:["myValue"],
        mounted:function () {
            console.log(this.myValue);
        }
    });
    new Vue({
        el:"#app"
    })
</script>
</body>

(2)子传父

<body>
<div id="app">
    <parent></parent>
</div>
<script src="../js/vue.min.js"></script>
<script>
    Vue.component("parent",{
        methods:{
            getData:function(msg){ //通过事件传递接受子组件的数据
                 console.log(msg);
            }
        },
        template:`
        <div>
            <h1></h1>
            <child @dataEvent="getData"></child>
        </div>
        `
    })
    Vue.component("child",{
        methods:{
            setData:function () {
                this.$emit("dataEvent","该交学费了");//触发绑定自定义事件dataEvent并且传递数据
            }
        },
        template: `
            <input type="button" @click="setData" value="传递数据">
        `
    })
    new Vue({
        el:"#app"
    })
</script>
</body>

(3)互相传值

<script>
    Vue.component("parent",{
        data:function(){
            return{name:"张三丰"}
        },
        methods:{
            getData:function(){ 
                 layer.msg("子组件的名字:"+this.$refs.mySon.name)
            }
        },
        template:`
        <div>
            <input type="button" @click="getData" value="获取子组件的数据">
            <child ref="mySon"></child>
        </div>
        `
    })
    Vue.component("child",{
        data:function(){
            return{name:"张无忌"}
        },
        methods:{
            setData:function () {
                layer.msg(this.$parent.name,{ offset:'t',anim:6})
            }
        },
        template: `
            <input type="button" @click="setData" value="传递数据">
        `
    })
    new Vue({
        el:"#app"
    })
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值