Vue父组件向子组件传递方法(自定义方法)并且子组件向父组件传递数据

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

    <script src="./lib/vue-2.4.0.js"></script>
</head>
<body>
    

    <div class="app">
        <!-- 父组件向子组件传递方法,使用的是事件绑定机制,v-on 当我们自定义一个事件属性之后,那么子组件就能够通过某些方法来
        调用,传递进去的这个方法了 -->
        <log v-bind:dataflog="msg" @funcshow="show" ></log>
    </div>


    <template id="log">
        <div>
            <h1>这是子组件界面----{{dataflog}}</h1>
            <input type="button" @click="myclick" value="父组件传递过来的方法 子组件接收">
        </div>
    </template>



    <script>
    
    var vm=new Vue({
        el:'.app',
        data:{
            msg:'看到数据了嘛'
        },
        methods: {
            // 父方法接受参数
            show(a){
            console.log(a.name+'父组件方法');
        },

            
        },
        components:{
            log:{
                template:'#log',
                props:['dataflog'],
                data(){
                        return {
                            duwei:{name:'duwei',age:30}
                        }
                },
                methods: {
                    myclick(){
                        // console.log('ok');
                        // 当点击子组件按钮的时候,如何拿到父组件传递过来的func 方法,并调用呢?
                        // emit英文愿意:是触发调用 发射的意思。
                        // this.$emit('funcshow')
                        // emit传递父组件中的方法,并且子组件向父组件传递消息
                        // this.$emit('funcshow',123,345)
                        this.$emit('funcshow',this.duwei);

                    },
                   
                },
            },
            
        }
    })
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/xiaowie/p/11640328.html