账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    vue 中$on()的this问题
    37
    0

    Vue.prototype.bus=new Vue();

        Vue.component('child',{
            template:`<div @click='handleClick'>{{text}}</div>`,
            props:{
                content:[String,Number]
            },
            data(){
                return {
                    text:this.content
                }
            },
            methods:{
                handleClick(){
                    this.bus.$emit('change',this.text)
                }
            },
            mounted(){
                var _this=this
                console.log(_this);
                this.bus.$on('change',function (msg) {
                        _this.text=msg
                        console.log(this);
                })
            }
        })
        var vm = new Vue({
            el:"#app",
        })
    

    上面代码中的 this.bus.$on('change',function (msg) {

                        _this.text=msg
                        console.log(this);
                })
            }

    里面的回调函数里面的this到底是指向谁?希望大佬帮忙解答一下,谢谢

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 高冷棉花 普通会员 1楼

      在 Vue 中,$on() 方法用于监听特定的事件,它会返回一个对象,这个对象可以用于绑定事件处理函数。然而,这个对象的 this 关键字并不总是指向定义它的元素,这可能会导致一些问题。

      以下是一个可能的情况:

      ```javascript // 触发事件 this.$emit('my-event', data);

      // 使用 $on() 监听事件 this.$on('my-event', function(data) { // 处理事件 });

      // 然后在其他地方尝试使用 this.$on(),但 this 没有指向你期望的元素 this.$on('my-event', function() { // 会抛出 TypeError,因为 this 没有指向数据本身 }); ```

      在这个例子中,事件处理函数没有正确地引用被监听的元素。正确的做法是确保这个函数有正确地引用了被监听的元素。

      例如,你可以这样定义事件处理函数:

      javascript this.$on('my-event', function(data) { // 处理事件 });

      然后在其他地方尝试使用 this.$on('my-event', function() { // 会抛出 TypeError,因为 this 没有指向 data }); ```

      在这个例子中,事件处理函数引用了被监听的元素,并且在函数中正确地引用了它。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部