1 回答

TA貢獻1818條經驗 獲得超8個贊
你有兩個選擇:
在類本身中定義手表
// 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)
添加回答
舉報