Vue组件的通信

一.Vue单层组件的通信:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Vue的全局组件</title>
    </head>
<body>
    <div id="app">
        <my-div message='思思最好了'></my-div>
        <my-div message='思思最棒了'></my-div>
    </div>
    <!-- 定义组件 -->
    <template id="my-div">
        <div><p>{{message}}</p></div>
    </template>

    <script src="js/vue.js"></script>
    <script>

        // 创建组件 注意这里要加#号,不然不能显示
        Vue.component('my-div', {
            template: '#my-div',
            props: ['message']
        });

        // 创建vue的实例
        let vm = new Vue({
            el: '#app',
            data: {
                name: 'si peng'
            },
        });
    </script>
</body>
</html>

二.多层组件的通信:必须通过动态绑定

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Vue多层组件间的通信</title>
    </head>
<body>
    <div id="app">
        <my-parent :imgsrc="img" :title="title"></my-parent>
    </div>
    <!-- 子组件1 -->
    <template id="my-image">
        <img src="imgsrc" width="200">
    </template>
    <!-- 子组件2 -->
    <template id="my-title">
        <he>{{title}}</he>
    </template>
    <!-- 父组件 -->
    <template id="my-parent">
        <div>
            <my-child1 :imgsrc='imgsrc'></my-child1>
            <my-child2 :title='title'></my-child2>
        </div>
    </template>
    <script src="js/vue.js"></script>
    <script>

        // 子组件的实例
        let child1 = Vue.extend({
            template: '#my-image',
            props: ['imgsrc']
        })
        let child2 = Vue.extend({
            template: '#my-title',
            props: ['title']
        })

        // 注册父组件
        Vue.component('my-parent', {
            props: ['imgsrc', 'title'],
            components: {
                'child1': child1,
                'child2': child2
            },
            template: '#my-parent'
        })

        // 创建vue的实例
        let vm = new Vue({
            el: '#app',
            data: {
                title: '思思,周末快乐啊!',
                img: 'images/3.jpeg'
            },
        });
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/pengsi/p/7784473.html