vue 父子组件通信实例

2019-01-06 23:30:01 阅读:4 编辑
<!doctype HTML>
<HTML lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Document</title>
</head>
<body>

<div id="App">
    <button v-on:click="show_modal ()">打开对话框</button>
    <child :content="message" ref="child" @select="select"></child>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/Ajax/libs/vue/2.5.17/vue.min.js">

</script>
<script>
    let Child = Vue.extend ({template: '<div v-show="open"><h2>{{content}}</h2>\
        <button v-on:click="close">关闭 </button><button v-on:click="select"> 选择</button></div>',
        props: {
            content: {
                type: String,
                default: () => {return 'from child'}
            },
        },
        data: function () {
            return {open: false,};
        },
        created: function () {console.log ("created");
        },
        methods: {close: function () {this.open = false;},
            // 会调用父类的方法
            select: function () {
                this.open = false;
                this.$emit ('select', this.content)
            },
            // 由父类来调用
            open_modal: function () {this.open = true;}
        }
    })

    new Vue ({
        el: '#App',
        data: {message: 'from parent2',},
        components: {child: Child},
        methods: {show_modal (){this.$refs.child.open_modal ();
            },
            select: function (value) {console.log ("select" + value);
            }
        }
    })
</script>
</HTML>