学习vue第十九节,父组件将方法传递给子组件

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="lib/vue-2.4.0.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body>
        
        <div id="app">
            <!-- 父组件可以通过事件绑定的形式,传递给子组件的数据(v-on 事件绑定缩写 @ ) -->
            <com1 v-on:parentshow='show'></com1>
            <p>{{childmsg}}</p>
        </div>
        <template id="temp">
            <div>
                <h2>我是模板内容!</h2>
                <button type="button" @click="cl">dianji</button>
            </div>
        </template>
        
        <script type="text/javascript">
            
            // 定义一个模板,组件中的components 直接调用就可以了
            var com1={
                template:'#temp',
                data(){
                    return {
                        msg:{name:"张三",old:16}
                    }
                },
                methods:{
                    cl(){
                        // $emit ,调用触发方法,可以传多个参数,或自己的属性
                        this.$emit('parentshow',123,this.msg)
                    }
                }
            }
            
            var vm=new Vue({
                el:'#app',
                data:{
                    msg:"我是一个父组件属性!!",
                    childmsg:""
                },
                methods:{
                    show(data,data2){
                        console.log("父组件被调用啦!"+data+data2.name+data2.old)
                        // 将子组件的值,赋值给父组件的属性,相当于父组件调用子组件的内容
                        this.childmsg=data2
                    }
                    
                },
                components:{                        
                    // 调用属性
                    com1
                    
                }
                
            })
            
            
        </script>
    </body>
</html>

 

posted @ 2020-06-08 19:51  三线码工  阅读(714)  评论(0编辑  收藏  举报