组件间的通信

1、父向子传值:

通过props传值

 <my-component :msg="msg"></my-component>

 //子组件
 Vue.component('my-component', {
    template: '#broTem',
    props: {
        'msg':String
    },
    created() {
        console.log(this.msg);
    }
});

2、子向父传值:

通过$emit传值

子组件

<template id="broTem">
    <div>
        <input type="button" value="我是子组件" @click="childMethods">
    </div>
</template>

Vue.component('my-component', {
    template: '#broTem',
    data() {
        return {
            msg: '子组件的数据'
        }
    },
    methods: {
        childMethods: function () {
            this.$emit('send-bro-msg', this.msg);
        },
    },
});

父组件

<div id="app">
    <my-component @send-bro-msg="sendBroMsg"></my-component>
</div>

new Vue({
    el: '#app',
    methods: {
        sendBroMsg: function (val) {
            console.log(val);
        }
    },
});

3、父组件调用子组件方法并传值(通过ref传值)

<div id="app">
    <input type="button" value="我是父组件" @click="parentMethods">
    <my-component ref="myCom"></my-component>
</div>


Vue.component('my-component', {
    template: '#broTem',
    methods: {
        childMethods: function (val) {
           console.log(val);
        }
    },
});

var vm = new Vue({
    el: '#app',
    data() {
        return {
            msg: '父组件的数据'
        }
    },
    methods: {
        parentMethods: function () {
            this.$refs.myCom.childMethods(this.msg);
        }
    },
});

4、子组件调用父组件方法并传值(通过$parent)

Vue.component('my-component', {
    template: '#broTem',
    data() {
        return {
            msg: '子组件的数据'
        }
    },
    methods: {
        childMethods: function () {
            this.$parent.parentMethods(this.msg);
        },
    },
});

var vm = new Vue({
    el: '#app',
    methods: {
        parentMethods: function (val) {
            console.log(val);//子组件的数据
        }
    },
});

5、子组件与子组件传值

发布了39 篇原创文章 · 获赞 2 · 访问量 4022

猜你喜欢

转载自blog.csdn.net/qq_43137725/article/details/103823690