user2449584
user2449584

Reputation: 83

Vue 3 + Typescript - How to watch a class property

I have recently started a project using CLI of Vue3 with Typescript and noticed that the vue-class-component is rather different. In fact, I am not sure if this project is really compatible with the latest Vue 3 functionality.

I came across these two threads: https://github.com/vuejs/vue-class-component/issues/406 and https://github.com/vuejs/vue-class-component/issues/406#issuecomment-745490016 so I am not sure if vue-class-component is the way to go these days.

Currently, I am trying to figure out how to Watch a property pass to a component but none of the stuff such as @Watch or @Prop are available anymore.

Can somebody provide an example on how to go about this?

Here is a snippet and I would like to know how to watch the msg property value:

<script lang="ts">
import { Options, Vue } from "vue-class-component";

@Options({
  props: {
    msg: String,
  },
})
export default class HelloWorld extends Vue {
  msg!: string;

}
</script>

Upvotes: 3

Views: 4599

Answers (2)

CunningFatalist
CunningFatalist

Reputation: 473

We use the vue-property-decorator package, and it works quite nicely.

https://github.com/kaorun343/vue-property-decorator#-watchpath-string-options-watchoptions---decorator

Edit: I just saw that you are using Vue 3 and I am note quite sure, if it is supported. I will still not delete this answer, because it might help you or someone else.

Cheers

Upvotes: 0

Nemlaghi.bechir
Nemlaghi.bechir

Reputation: 131

For Vue 2 you would use vue-property-decorator

For Vue 3 - for now - you can use vue-facing-decorator which has a complete implementation of decorators.

Both repositories have similar usage:

// import { Prop, Watch, Component, Vue } from " vue-property-decorator"; // Vue2
import { Prop, Watch, Component, Vue } from "vue-facing-decorator"; // Vue3

@Component
export default class HelloWorld extends Vue {
  @Prop
    msg: string
  
  @Watch('msg')
  methodName (newMsg: string, oldMsg: string) {
    console.log(`msg just changed from ${oldMsg} to ${newMsg}`);
  }
}

Edit: vue-property-decorator recently started supporting Vue 3, as for today there is a release candidate : npm install [email protected], further releases might be more stable.

Upvotes: 5

Related Questions