全局组件间的传参(子传父)

在子组件上创建一个自定义方法,这个自定义方法的处理函数是父组件里的方法,子组件触发这个方法。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>子组件控制父组件</title>
    <style>
        .show{
            width:100px;
            height: 100px;
            text-align: center;
            font-size: 20px;
            line-height: 100px;
            background-color: rgba(0,0,136,0.36);
        }
    </style>
</head>
<body>
<div id="app">
    <father></father>
</div>
<template id="father">
    <div>
        father
        <button @click="show">show/hide</button>
        <div class="show" v-if="showState"></div>
        <hr>
        <son @test="show"></son>
    </div>
</template>
<template id="son">
    <div>
        son
        <button @click="sclick">点击</button>
    </div>
</template>
<script src="vue.js"></script>
<script>
    Vue.component('father',{
        template:"#father",
        data(){
            return{
                showState:true
            }
        },
        methods:{
            show(){
                this.showState=!this.showState;
            },
            sayHellow(){
                console.log('你好');
            }
        }
    })
    Vue.component('son',{
        template:"#son",
        data(){
            return{

            }
        },
        methods:{
            sclick(){
                console.log('点击子组件的button');
                this .$emit('test');
            }
        }
    })
    new Vue({
        el:"#app"
    });
    //在子组件上创建一个自定义方法
//    这个自定义方法的处理函数是父组件的方法,由子组件触发这个方法
</script>
</body>
</html>

结果截图:(点击子组件按钮可以控制父组件内的显示与隐藏)

猜你喜欢

转载自blog.csdn.net/hemeng0115/article/details/85233372