robskrob
robskrob

Reputation: 2898

How to create and use computed property's setter with the composition API

I have a Vue 2 app and it's using the composition API package so that I can create vue components with composition API.

How does one create and use a setter for a computed property with the Vue composition API?

I am looking at the docs, and I do not see any documentation for creating a setter for a computed property. In the test suite, I see an example:

 const b = computed({
   get: () => a.value + 1,
   set: (v) => (a.value = v - 1),
 })

However I am not too sure how to access the set method on b. Does anyone know how to create a computed property with a set method for the composition API? And how can I use the set method so I can change the computed property's value?

Upvotes: 4

Views: 17658

Answers (1)

Nechoj
Nechoj

Reputation: 1582

In a vue3 component, you would use it like this:

<template>
  <p>a={{ a }} b={{ b }}</p>
  <button @click="b = 3">Click me</button>
</template>

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

const a = ref(1);
const b = computed({
  get: () => a.value + 1,
  set: (v) => (a.value = v - 1),
})
</script>

The setter for b is called when clicking the button (assignment b = 3)

An alternative is to use computed section inside the <script> tag (options api, without the <script setup> section):

<template>
  <p>a={{a}} b={{b}}</p>
  <button @click="b = 3">Click me 1</button>
</template>


<script>
export default {
  name: "Test",
  data(){
    return {
      a: 1
    }
  },
  computed: {
    b:{
      get(){return this.a + 1;},
      set(v){this.a = v - 1;}
    }
  }
}
</script>

Upvotes: 9

Related Questions