组件自定义事件(子传父组件)-$emit

案例:将子组件Student中的name传给父App组件

Student组件

复制代码
<template>
    <div class="student">
        <h3>学生姓名:{{name}}</h3>
        <h3>学校性别:{{sex}}</h3>
        <button @click="sendStuName">点我把学生名给App</button>
    </div>
</template>
<script>

export default {
    data(){
        return{
            name: '张三',
            sex: ''
        }
    },
    methods: {
        sendStuName(){
            //触发Student组件实例身上的getStuName事件
            this.$emit('getStuName',this.name)
        }
    },    
}
</script>
<style scoped>
    .student{
        background-color: pink;
    }
</style>
复制代码

App组件

复制代码
<template>
  <div id="app">
    <h1>{{msg}}</h1>
    <school></school>
    <Student @getStuName="getStuName"></Student>
  </div>
</template>

<script>
import School from './components/School'
import Student from './components/Student'

export default {
  name: 'App',
  components: {
    School,Student
  },
  data(){
    return{
      msg: '你好啊'
    }
  },
  methods: {
    getStuName(name){
      console.log('app收到了学生姓名:',name);
    }
  },
}
</script>

<style>
</style>
复制代码

 

 

 

 

 

 

 

posted @   iTao0128  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示