ts 重写 vue 项目的时候 this 指向问题

image.png
源码

interface VueOptions {
 el?:string,
   methods: object;
   data(): object;
   mounted?: object;
   created?: object;
}
interface Data{
 msg:string
}
class Vue {
   private $data = {};
   constructor(options: VueOptions) {
       this.$data = this.initData(options.data);
   }
   initData(data: object) {
       if (typeof data === 'function') return data();
       else return data;
   }
}
const app = new Vue({
 el:'#app',
   data() {
       return {
           msg: '呃呃呃呃呃',
           name: 'mike',
           age: {
               max: 19,
           },
       };
   },
   methods: {
       setName() {
           this.msg = '哈哈';
       },
   },
});

如图 本人在用 ts 写简单的 vue 响应式的时候出现 this 问题
请大佬指教如何修复(本人 ts 小白 见谅)

阅读 6.8k
5 个回答

使用 vue-property-decorator

为什么自己重新定义了Vue?

如果使用自己重新定义的Vue,不是很清楚你是怎么实现的,但看到VueOptions中的data类型是object,object表示的是{},也就是其中没有任何property的空对象,this自然也找不到msg。

如果直接使用Vue@2.6.11(因为我自己在这个版本下,不清楚其他版本有没有实现),是能够实现自动推断的,这样写并不会报错。

如果发现没有自动推断,那么可以这样写。其中Vue接收的第一个泛型类型即表示的是data的类型,例如下面的写法中,data有msg这个property。

new Vue<{ msg: string }>({
data() {
       return {
           msg: 'foo',
       };
   },
   methods: {
       setName() {
           this.msg = 'bar';
       },
   },
})

ps: vue@2版本使用class style能够获得更好的编程体验

vue 根节点上的响应数据使用data对象,只有非根组件才使用data方法,像下面这样

var app3 = new Vue({ 
      el: '#app-3', 
      data: { seen: true } 
    })
新手上路,请多包涵

其实这个很简单的,自己写个方法,重新定义下就可以了, 自己可以优化,随便写写的

class main {
    test = '';
    message = 'Hello Vue!';
    reverseMessage() {
        this.message = 'A';
        this.test = 'B';
        this.test1();
    }
    test1() {
        alert(111);
    }
    onReady() {
        // yeyu.ui.open();
        // yeyu.wechat('wxbaed3a1db01ca305', 'https://yeyu.cn/app/');
    }
    created() {
    }
}

Page(new main()); 
function Page(config) {
    for (var key in config) {
        var val = config[key];
        config.data = config.data || {};
        config.methods = config.methods || {};
        if (typeof val != "function") {
            config.data[key] = val;
            delete config[key];
        } else {
            if ('onReady|created'.indexOf(key) >= 0) {
                delete config[key];
            } else {
                config.methods[key] = val;
            }
        }
    }
    config.el = '#app';
    return new Vue(config);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题