Search code examples
vue.jsvue-componentvue-class-componentsvue-property-decorator

How to access computed state variable?


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>

Solution

  • 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