问题描述
基本上,我在Github上有与this和this问题相同的问题,不幸的是,这两个问题在被回答之前都已关闭:/
我正在将Vue与Typscript和Vue类组件一起使用。
我需要做的是从@Component装饰器中的观察者内部访问(Vue-)类的方法。
我知道可以使用this.$data
访问组件的数据,但是方法呢。
我的代码可在运行时运行,但会在vscode中产生编译时错误和错误(“类型'Vue'中不存在属性'clearInfo'。”);
@Component({
watch: {
firstMesh(newMesh) {
if (newMesh === undefined) this.clearInfo(1); // this produces the errors
else this.showMeshInfo(newMesh,1);
},secondMesh(newMesh) {
if (newMesh === undefined) this.clearInfo(2);
else this.showMeshInfo(newMesh,2);
},},})
export default class Info extends Vue {
clearInfo(whichMesh : number) {
...
}
showMeshInfo(mesh : any,index : number) {
....
}
}
解决方法
您有两个选择:
- 在班级中定义手表
// first you need to install vue-property-decorators with npm i -S vue-property-decorator
// This library has a lot of useful decorators. You can read more about it here: https://github.com/kaorun343/vue-property-decorator
import { Vue,Component,Watch } from 'vue-property-decorator'
@Component
export default class Info extends Vue {
@Watch('firstMesh')
public watchFirstMesh(newValue) {
// ... do whatever you need to do with the newValue here
}
@Watch('secondMesh')
public watchSecondMesh(newValue) {
// ... do whatever you need to do with the newValue here
}
}
- 在@Component的选项部分中定义手表和方法
@Component({
watch: {
firstMesh(newMesh) {
if (newMesh === undefined) this.clearInfo(1); // this produces the errors
else this.showMeshInfo(newMesh,1);
},secondMesh(newMesh) {
if (newMesh === undefined) this.clearInfo(2);
else this.showMeshInfo(newMesh,2);
},},methods: {
clearInfo(whichMesh : number) {
...
},showMeshInfo(mesh : any,index : number) {
....
}
}
})
export default class Info extends Vue {
// Now you need to tell to typescript that there will be a method inside this class called clearInfo and showMeshInfo
public clearInfo!: (wichMesh: number) => void;
public showMeshInfo!: (mesh: any,index: number) => void;
}
说明
-
解释可以在我留下的链接上阅读
-
由于您正在装饰器
@Component({...})
中定义选项,因此在实例化该类的上下文中将可用。 Typescript不知道确切可用的内容(我们希望它这么聪明)。您必须告诉它,这就是我们拥有public clearInfo!: (wichMesh: number) => void;
部分的原因。如果您不知道此语法的含义,我将用简短的单词进行解释,并在最后留下一个链接:
public clearInfo!: (wichMesh: number) => void;
the ! part is called the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null or undefined here,so don't complain about the possibility of it being null or undefined."
The (wichMesh: number) => void; is the function signature. Basically it says: this will be a function that receives as the first argument a number (whichMesh) and returns void (=> void)