14

I have below code for a computed property.

computed: {
  filterText: {
    get() {
      return this.filter; // it's a vuex state
    },
    set(value) {
      this.setFilter(value); // it's a vuex action
    }
  }
}

Now, I want to write it in class-based components. I think getter should be like this, but how to write setter?

get filterText() {
  return this.filter
}
0

1 Answer 1

33

Class based components use get and set for computed properties:

get filterText() {
  return this.filter
}

set filterText(value) {
  this.filter = value
}

A single file component written in TypeScript would be structured like:

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

  @Component
  export default class MyClass extends Vue {
    private filter: string = ''

    public get filterText(): string {
      return this.filter
    }

    public set filterText(filter: string) {
      this.filter = filter
    }
  }
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

How do I call the set method?
@farahm this.filterText = value
@farahm Actually, it should already work with <component v-model="filterText"/>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.