美文网首页
02_08.组件父传子

02_08.组件父传子

作者: Robyn_Luo | 来源:发表于2017-11-12 19:11 被阅读0次
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        [v-cloak] {
            display: none;
        }
    </style>
</head>
<body>
    <div id="app">
        <!-- 父通过属性的方式给子传递数据 -->
        <app-header v-bind:tit="title"></app-header>
        <app-header v-bind:tit="title2"></app-header>
    </div>
    
    <script id="header-tpl" type="text/tpl">    
        <header>
            <h1>{{ tit }}</h1>
            <span>{{ content }}</span>
        </header>
    </script>

    <script src="vue.js"></script>
    <script>
        // 搞一个公共的页面头部组件
        Vue.component('app-header', {
            props: ['tit'],    // 子通过props配置项接收来自父的数据
            template: '#header-tpl',
            data: function() {
                return {
                    content: '这是一个神奇的网站, 85同城!'
                };
            }
        });

        // 数据父传子大概需要两步: 
        // 1: 父在使用子组件的时候, 通过标签属性的形式给子组件传递数据
        // 2: 子通过props配置项接收
        var vm = new Vue({
            el: '#app',
            data: {
                title: '详情页',
                title2: '首页'
            }
        });
    </script>
</body>
</html>

相关文章