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

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

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    在vue的data里面 new对象 绑定这个对象的方法 this 指向为null
    • 2020-01-01 00:00
    • 11
    27
    0

    在vue的data里面 new对象 绑定这个对象的方法 this 指向为null
    我在vue 外写了一个类写了一些自定义方法,
    我不想在methods新加多余的函数 如何解决。。

    <div id="app">
        <div class="a" @click="mouse.click"></div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        class mouse {
            constructor() {
                this.a = 0
            }
            click(e) {
                console.log(this) 
                //这里打印出来是null
            }
            
        }
        var app = new Vue({
            el: '#app',
            data() {
                return {
                    mouse: new mouse()
                }
            }
        })
    </script>
    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    • 曳白 普通会员 1楼

      在Vue.js中,当你在数据的 data 属性中创建一个新对象,并将其绑定到数据源 this 指针上时,如果你试图访问 this 指针,但实际上它指向的是创建新对象时的指针,而不是当前正在操作的对象的指针。这可能会导致一些奇怪的行为,例如: 1. 错误的 this 指针访问:如果你在 this 指针上绑定一个方法,尝试在方法调用时访问 this 指针,这将导致 Vue 库中的错误。这是因为 this 指针在新对象被创建后将指向 this 指针,而不是当前对象的指针。例如: javascript data() { let obj = new Object(); obj.name = 'John'; obj.sayHello = function() { console.log(this.name); // 输出: John }; return obj; }, 在上面的代码中,this 指针在创建 obj 对象后将指向 this 指针,因此尝试访问 this.name 的调用将返回 undefined,因为 this 指针此时指向 obj 对象,而不是当前对象的指针。 2. 错误的 this 指针访问:如果你尝试在方法内部访问 this 指针,这通常会导致运行时错误。例如: javascript data() { let obj = new Object(); obj.name = 'John'; obj.sayHello = function() { this.name = 'Alice'; }; return obj; }, 在上面的代码中,尝试在 sayHello 方法内部访问 this.name 的调用将导致运行时错误,因为 this 指针在创建 obj 对象后将指向 this 指针,而不是当前对象的指针。如果你尝试在方法内部访问 this,而不是在方法外部,它将正常工作,因为在 Vue 中,方法是通过 this 指针来访问的,因此不会导致运行时错误。 为了避免这些问题,你可以考虑以下几种方法:

      1. 使用箭头函数或 ES6 的 this 关键字来重写方法: javascript data() { let obj = new Object(); obj.name = 'John'; obj.sayHello = (this.name) => { console.log(this.name); // 输出: Alice }; return obj; }, 在上面的代码中,我们使用箭头函数或 ES6 的 this 关键字来重写 sayHello 方法,使 this 指针在方法调用时指向 obj 对象的 name 属性。

      2. 使用 setThis 方法: javascript data() { let obj = new Object(); obj.name = 'John'; obj.sayHello = () => { this.setThis('Alice'); }; return obj; }, 在上面的代码中,我们使用 setThis 方法来重写 sayHello 方法,将 this 指针设置为 obj 对象的 name 属性。

      3. 使用箭头函数的 this 关键字调用方法: javascript data() { let obj = new Object(); obj.name = 'John'; obj.sayHello = (this.name) => { console.log(this.name); // 输出: Alice }; obj.sayHello(); // 输出: Alice } 在上面的代码中,我们使用箭头函数的 this 关键字调用 sayHello 方法,使得 this 指针在方法调用时指向 obj 对象的 name 属性,而不是当前对象的指针。

      通过使用上述方法,你可以正确地访问和操作 this 指针,避免出现上述问题。例如: javascript data() { let obj = new Object(); obj.name = 'John'; obj.sayHello = (this.name) => { console.log(this.name); // 输出: Alice }; obj.sayHello(); // 输出: Alice obj.sayHello(); // 输出: Alice } 这样,你可以在方法调用时正确地访问和操作 this 指针,确保它指向 obj 对象。

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