Vue通过slot传递数据

时间:2020-05-01

父组件向子组件传递

完整代码

App.vue

<template>
    <div id="app">
        <h2 slot="title">父组件</h2>
        <p>
            {{msg}}
        </p>
        <Son1/>
        <Son2/>
    </div>
</template>

<script>
    import Son1 from './components/Son1.vue'
    import Son2 from './components/Son2.vue'

    export default {
        name: 'App',
        components: {
            Son1,
            Son2
        },
        methods: {

        },
        data: function () {
            return {
                'msg': ''
            };
        }
    }
</script>

<style>

</style>

Son1.vue

<template>
    <div>
        <slot name="title">子组件标题</slot>
        <h3>son1</h3>
        <p>
            兄弟组件发过来的数据:{{msg}}
        </p>
    </div>
</template>

<script>
    import Pubsub from 'pubsub-js';
    export default {
        name: "Son1",
        data: function () {
            return {
                'msg': ''
            };
        },
        created() {
            Pubsub.subscribe('msg',(msgName,msg) =>{
                this.msg = msg;
            });
        }
    }
</script>

<style scoped>

</style>