Vue中子组件调用父组件的方法

Vue中子组件调用父组件的方法

相关Html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../js/vue-2.4.0.js"></script>

    <style>

    </style>
</head>
<body>
<div id="app">
    <!--父组件可以在引用子组件的时候,通过属性绑定的形式(v-bind:),-->
    <!--把需要传递给子组件的数据,以属性绑定的形式传递到子组件中 给子组件使用-->

    <com2 @func="show"></com2>
</div>

<template id="temp1">
    <div>

        <h1>这是子组件</h1>
        <input type="button" value="这是子组件按钮 点击后触发父组件的func方法"

               @click="myclick"
        >
    </div>
</template>

<script>
    var com2 = {
        template: '#temp1',
        data: function () {
            return {
                sonmsg: {name: '大头儿子', age: 6}
            }

        },
        methods: {
            myclick: function () {
                //当点击子组件的按钮的时候如何拿到父组件的func方法 并调用
                //$emit() 原意:触发
                //第二个参数可以传参
                this.$emit('func', this.sonmsg);
                console.log('ok');

            }

        }
    }

    var vm = new Vue({
        el: '#app',
        data: {
            datamsgFromSon: null
        },
        methods: {
            show: function (data) {
                console.log("调用了父组件的func,并且data为:" + data);
                console.log(data);
                this.datamsgFromSon = data;
            }

        },
        components: {
            com2: com2
        }
    });

</script>

</body>
</html>

猜你喜欢

转载自www.cnblogs.com/charlypage/p/9901329.html