Vue 子组件给父组件传值

使用组件的自定义事件来完成:子组件给父组件传值

使用场景:子给父传数据,需要在父组件中给子组件绑定自定义事件(事件的回调在父组件中


实例

父组件 App.vue

<template>
    <div class="app">
        <h2>{{msg}}</h2>
        <h2>学生姓名为:{{StudentName || '未收到'}}</h2>
        <my-student @hellodemo="getStudentName"/>
    </div>
</template>

<script>

    import MyStudent from "@/components/MyStudent";

    export default {
        name: 'App',
        components: {MyStudent},
        data() {
            return {
                msg: '你好',
                StudentName: ''
            }
        },
        methods: {
            getStudentName(name) {
                console.log('App 收到学生名称:', name)
                this.StudentName = name
            }
        },
    }
</script>

<style scoped>
    .app {
        background-color: #979696;
        padding: 5px;
    }
</style>

子组件 MyStudent.vue

<template>
    <div class="student">
        <h2>学生姓名:{{name}}</h2>
        <h2>学生年龄:{{age}}</h2>
        <button @click="sendStudentName">把学生名给 App</button>
    </div>
</template>

<script>
    export default {
        name: "MyStudent",
        data(){
            return {
                name:'张三',
                age:19
            }
        },
        methods:{
            sendStudentName(){
                this.$emit('hellodemo',this.name)
            }
        }
    }
</script>

<style scoped>
    .student{
        background-color: #b2dece;
        padding: 5px;
        margin-top: 30px;
    }
</style>


posted @ 2022-05-17 09:46  春暖花开鸟  阅读(42)  评论(0编辑  收藏  举报