Vue学习:组件自定义事件(this指向)(原生事件)

APP收到信息,需要在页面展示

v-on的方式

  this.studentName=name
<template>
    <div class="app">
        <h1>{{msg}},APP收到的学生姓名是:{{studentName}}</h1>
        <!-- : 传递的就变成了表达式-->
        <!-- Student组件实例对象 绑定了mything事件  mything触发实现的回调函数demo -->
        <!-- 通过父组件给子组件绑定自定义事件实现:v-on子给父传递数据 -->
           <Student v-on:mything="getStudentName"/>
            <!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
            <School :getSchoolName="getSchoolName"/>
           
            </div>
        </template>

        <script>
    //引入<School/>组件
    import Student from './components/Student'
    import School from './components/School'
    export default {
        name: 'App',
        data() {
            return {
                msg:'你好',
                studentName:''
            }
        },
        //注册组件
        components: { 
            Student,
            School 
        },
        methods: {
            getSchoolName(name){
                console.log('APP收到了学校名',name)
            },
            getStudentName(name,...a){
                console.log('APP收到了学生名',name,a)
                this.studentName=name
            },

        },
    

     

    };
</script>
        <style>
    .app{
        background-color: #bfa;
        padding: 5px;
    }
</style>

ref的方式

  <Student ref="student"/>


 mounted() {
          //收到了组件实例对象 this.$refs.student
          this.$refs.student.$on('mything',this.getStudentName)
}

    getStudentName(name,...a){
                console.log('APP收到了学生名',name,a)
                this.studentName=name
            },

但是这里有一个注意事项

   this.$refs.student.$on('mything',function(...args) {
            console.log(this)
            
        })

this是student组件实例,谁触发 this是谁

this是vc了箭头函数没有自己的this ,所以指向了app

          this.$refs.student.$on('mything',(...args)=>{
            console.log(args)
            console.log(this)//vc
            this.studentName=args[0]

          })

前面都是给组件绑定自定义事件,现在是原生事件

    <Student ref="student" @click="show"/>

这种写法变成了自定义事件 需要一个修饰符native

     <Student ref="student" @click.native="show"/>
       

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值