vue的子组件给父组件传值的方法


app组件的代码

<template>
    <div class="d1">
        <!-- 两种子给父传值的方法 -->
<!-- 第一种是父给子先传递函数 子组件要用props接收数据,然后调用函数,给父组件返回值--> <MyStudent :getStudentName="getStudentName"></MyStudent>
<!-- 第二种是父亲给子定义自定义函数,子组件只需要用this.$emit('aiguigu',返回值) 触发函数就可以了,这时父亲就可以收到返回值 --> <MySchool v-on:aiguigu="getSchoolName"></MySchool> </div> </template> <script> import MyStudent from './components/MyStudent.vue' import MySchool from './components/MySchool.vue' export default { name:'App', components:{ MyStudent, MySchool }, data() { return { } }, methods: { getStudentName(name){ console.log('我收到了来自学生的名字',name) }, getSchoolName(name){ console.log('我收到了来自学校的名字',name); } }, } </script>

MyStudent的代码

<template>
    <div id='student'>
            
            <h2>我的名字是:{{name}}</h2>
            <h2>我的年龄是:{{age}}</h2>
            <button @click="sentStudentName">点我给app发送名字</button>
            
            
    </div>
</template>

<script>
    
    export default {
        name:'MyStudent',
        data() {
            return {
               name:'王哥',
               age:'23'              
            }         
        },
        //接受app传过来的函数
        props:['getStudentName'],//记得加分号
        methods: {
            //把学生姓名传回去
 sentStudentName(){ this.getStudentName(this.name) }
        },
        
        
    }
</script>

MySchool的代码

<template>
    <div id="school">
        <h2>学校名字是{{name}}</h2>
        <h2>学校地址是{{address}}</h2>
        <button @click="sentSchoolName">点我调用app的demo函数</button>
    </div>
</template>

<script>
   
    export default {
        name:'MySchool',
        data() {
            return {
                name:'广州****大学',
                address:'广州'
            }
        },
        methods: {
            sentSchoolName(){ this.$emit('aiguigu',this.name) }
        },
        

    }
</script>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM