为了账号安全,请及时绑定邮箱和手机立即绑定

从观察者内部的 Vue 类组件装饰器访问方法

从观察者内部的 Vue 类组件装饰器访问方法

精慕HU 2023-05-18 11:09:20
我将 Vue 与 Typscript 和 Vue 类组件一起使用。我需要做的是从 @Component 装饰器内的观察者内部访问我的(Vue-)类的方法。我知道可以使用 访问组件的数据this.$data,但是方法呢?我的代码在运行时运行,但在 vscode 中产生编译时错误和错误(“属性‘clearInfo’在‘Vue’类型上不存在。”);@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) {    ....  }}
查看完整描述

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;

}

解释

  1. 可以在我留下的链接上阅读解释

  2. 由于您是在装饰器中定义选项,因此@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)


查看完整回答
反对 回复 2023-05-18
  • 1 回答
  • 0 关注
  • 121 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号