从方法访问vue组件中的数据

问题描述 投票:3回答:2

我目前在正确的上下文中在VueJs组件中使用“this”时遇到了麻烦。我已经阅读了很多答案,主要是指不使用箭头功能。正如你在我附加的代码块中看到的那样,我已经用常规代码替换了箭头函数,并且很好......上下文现在不同但是关于错误消息


"TS2339: Property 'answer1' does not exist on type '{ receiveValues(value1: string, value2: string): void; test(): string; }'."
the context is now the methods object. I wasted a lot of time now with this problem and I really don't know what to do. So my question is, how can I get the right context to access the data? I appreciate every help and tipps! I use the ts compiler with ES2015.
Code:
export default {
name: 'app',
components: {
  Editor,
  Chart,
},
methods: {
  receiveValues(value1: string, value2: string) {
    console.log(value1); 
    this.answer1 = value1; // This is where the error is thrown
    console.log('receiveValues ' + this.test()); // this works just fine
  },
  test() {
    console.log('blablabla');
    return 'did it';
  },
},
data() {
  return {
    content: 'I\'m Test Content!',
    answer1: '',
    answer2: '',
    answer3: '',
    answer4: '',
  };
},


Unlike in this post for example, my 'this' context only refers to the methods object, so I can only call its functions, but not the data from the component itself.
typescript vue.js ecmascript-6 components
2个回答
0
投票

对于所有遇到同样问题的人:我仍然不知道为什么我无法使用'this'访问正确的上下文,但我找到了一个对我有用的解决方案:


I used typescript decorators for class files from Vue Class Component and now it works! In my opinion the code is even easier to write and cleaner! Thanks to @Michał Perłakowski and @Max Sinev for their help.

0
投票

来自Max Sinev的一个答案的评论确实对我很有帮助,但对其他人来说可能很容易错过,所以重新发布:

你使用Vue.extend或Component生成器在Typescript中声明你的组件?看起来你只是使用javascript中的普通对象来表示不正确的Vue组件

我不小心使用了一个普通的物体,并且看到了各种各样的问题。换到Vue.extend({})排序了一切。

© www.soinside.com 2019 - 2024. All rights reserved.