vue 组件 通讯 繁體版
原文   原文链接

一.Vue单层组件的通讯:html

<!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>

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

<!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>
相关文章
相关标签/搜索
每日一句
    每一个你不满意的现在,都有一个你没有努力的曾经。
本站公众号
   欢迎关注本站公众号,获取更多信息