如何理解Vue中组件的自定义事件

发布时间:2021-11-22 09:16:40 作者:柒染
来源:亿速云 阅读:120

本篇文章为大家展示了如何理解Vue中组件的自定义事件,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

如何理解Vue中组件的自定义事件

<template>
  <div >
    <h3>{{msg}}</h3>
    <!-- 通过父组件给子组件传递函数类型的数据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">
    <h3>学生姓名:{{name}}</h3>
    <h3>学生年龄:{{age}}</h3>
    <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中组件的自定义事件,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. vue 组件的理解
  2. 用实例解析vue如何使用自定义事件的表单输入组件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue

上一篇:如何理解Java中左移和右移问题

下一篇:c语言怎么实现含递归清场版扫雷游戏

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》