How to access computed state variable?

323 views Asked by At

Using Vue Class Component, how does one get the value of a computed variable? Trying to use this.bar gives an error: Property 'bar' does not exist on type 'Vue'.

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";

@Component({
    computed: {
        bar() {
            return true;
        },
    },
    methods: {
        qux() {
            // How to get the value of bar here?
            if (this.bar) {
                baz();
            }
        },
    },
})
export default class Foo extends Vue {}
</script>
3

There are 3 answers

0
Tony On BEST ANSWER

That's because you are not using the right syntax.

You should change what you have to this

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";

@Component  
export default class Foo extends Vue {
  get bar(): boolean {
    return true;
  }
  qux() {
    if (this.bar) {
        baz();
    }
  }
}
</script>

For more on using Vue Class Components, check out this article

0
Dawid Kisielewski On

Any reason why you do not wanna use getter?

@Component({})
export default class Foo extends Vue {
  get bar() { return true }
}

This is converted to computed property

0
Alonad On

If you use vue-property-decorator everything goes to extended class.

Normal Vue:

export default {
  data(){
    return {}
  },
  computed: {
    bar() {
        return true;
    },
  },
  methods: {
    qux() {
        if (this.bar) {
            baz();
        }
    }
  }
}

The same in Typescript

@Component({})

export default class Foo extends Vue {
  get bar() {
    return true;
  }

  private qux() {
    if (this.bar) {
      this.baz();
    }
  }

  private baz() {
    //do smth
  }
}