华域联盟 JavaScript Vue之组件的自定义事件详解

Vue之组件的自定义事件详解

文章目录[隐藏]

目录

<template>
  <div >
    <h2>{{msg}}</h2>
    <!-- 通过父组件给子组件传递函数类型的数据props实现:子给父传递数据 -->
<School :getName="getName"/>
<Student :getStudentname="getStudentname"/>
<!-- 通过父组件给子组件绑定一个自定义事件:实现子给父传递数据 -->
<Age v-on:elderSex="demo"/>
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法:使用ref) -->
   <!-- <Student ref="student"/> -->
  </div>
</template>
<script>
import School from './components/School.vue'
import Student from './components/Student.vue'
import Age from './components/Age.vue'
export default {
name:'App',
components:{ School,Student ,Age},
data(){
  return {
    msg:'你好,世界!'
  }
},
methods:{ 
  getName(name){
    console.log('App收到了名字',name);
  },
  getStudentname(name1){
    console.log('接收到了学生的姓名',name1);
  },
  demo(sex1){
    console.log( 'demo被调用了',sex1);
  }
},
// mounted() {
  //绑定自定义事件
//   this.$refs.student.$on('elderSex',this.schoolAge)
//绑定自定义事件(一次性)
//   this.$refs.student.$once('elderSex',this.schoolAge)
// },
}
</script>
<style scoped>
</style>
<template>
  <div class="demo">
    <h2>学生姓名:{{name}}</h2>
    <h2>学生年龄:{{age}}</h2>
    <button @click="sendStudentname">把学生的名字给APP</button>
  </div>
</template>
<script>
  export default {
    name: 'Student',
    props: ['getStudentname'],
    data() {
      return {
        name: '张三',
        age: 19
      }
    },
    methods: {
      sendStudentname() {
        this.getStudentname(this.name)
      }
    }
  }
</script>
<style>
  .demo {
    background-color: skyblue;
  }
</style>

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注华域联盟的更多内容!

本文由 华域联盟 原创撰写:华域联盟 » Vue之组件的自定义事件详解

转载请保留出处和原文链接:https://www.cnhackhy.com/147297.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们