how to write computed setters in class-based compo

2020-08-18 07:53发布

问题:

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
}

回答1:

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>