1. 程式人生 > 其它 >Vue 子元件給父元件傳值

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>