Join my Laravel for REST API's course on Udemy 👀

Getters and Setters for computed properties in Vue.js

May 1, 2022  ‐ 2 min read

By default computed properties are getter-only, that is, you can access the property but not assign it a value. The value should, normally, be derived from other reactive properties. Vue makes sure to re-evaluate the computed property once a reactive property used in the computed property changes.

If you were to try to assign a value to a computed property you will receive the Runtime Error:

Computed property "..." was assigned to but it has no setter.`

One thing to consider if you want to assign a value to a computed property is whether your computed property shouldn't be a data property instead, or can achieve the same result using a watcher.

But if computed properties really suit your use-case then you can provide a custom getter and setter function to the computed property.

You may do so by turning the computed property into an object instead of just a method. This object should contain both a setter and a getter method, the setter method takes the value that you assign the computed property as the first argument.

Take the following as an example, it uses the Vue options API, and defines a custom getter and setter for the slug computed property.

<script>
  import slugify from "slugify";

  export default {
    data() {
      return {
        slugValue: "",
      };
    },
    computed: {
      slug: {
        set(value) {
          this.slugValue = slugify(value);
        },
        get() {
          return slugify(this.slugValue);
        },
      },
      created() {
        this.slug = "Hey There";
      },
    },
  };
</script>

If you are using the composition API then the approach doesn't differ as much. You achieve the same result by providing an object with getter and setter methods to the computed() function.

<script setup>
  import slugify from "slugify";
  import { ref, computed } from "vue";

  const slugValue = ref("John");

  const slug = computed({
    // getter
    get() {
      return slugify(slugValue.value);
    },
    // setter
    set(value) {
      // Note: we are using destructuring assignment syntax here.
      slugValue.value = slugify(value);
    },
  });
</script>