Props in vue 3 is not accessible in class base component

Viewed 3394

I am migrating to vue 3 . I am not be able to access the props value in my class instead it gives me 0 and not printing in console the latest value i am using on prop. On template it working fine but i want the latest value of titleComponent in my class

import { Options, Vue } from "vue-class-component";
    
@Options({
  props: {
    titleComponent: Number
  }
})
    
export default class StorePin extends Vue {
  private titleComponent = 0;
    
  mounted()
  {
    console.log(this.propValue);
  }
 
  get propValue()
  {
    return this.titleComponent;
  }
   
  incremnt()
  {
    this.titleComponent ++ ;
  }
  
}
3 Answers

Create a Props-class where you declare your props, and then add it to the component by using the .with() method on it! This will give you great TypeScript-support, and you don't even have to use the PropType interface from the "@vue/runtime-core" library.

<template>
  <p>Hello world</p>
</template>

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

class Props {
  array: string[] = prop({
    required: true,
  });
}

@Options({})
export default class MyComponent extends Vue.with(Props) {
}
</script>

<style lang="scss" scoped>
</style>

Props are supposed to be readonly, so if you want to modify titleComponent in your component, you'll need to modify a local copy (e.g., from a watcher):

import { Options, Vue } from "vue-class-component";

@Options({
  props: {
    titleComponent: Number
  },
  watch: {
    titleComponent(val) {
      this._titleComponent = val;
    }
  }
})
export default class StorePin extends Vue {
  private _titleComponent = 0;

  get propValue()
  {
    return this._titleComponent;
  }

  increment()
  {
    this._titleComponent++;
  }
}

you can access props through oop! just like code down below. VUE3 & TS

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

export class Props {
  name = prop<string>({ required: false });
  link = prop<string>({ required: true });
}

export default class SolarButton extends Vue.with(Props) {
  visitRout() {
    console.log("this.name", this.name);
    console.log("this.link ", this.link);
    this.$router.push(this.link);
  }
}
</script>
Related