Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the current value of a computed property within that computed property method?

We would like to enable a query once a string has more than 3 characters. Once the query is enabled, it should stay enabled. Using the Vue 2 Composition API we created a reactive object with the status of the queries:

import { computed, defineComponent, reactive, ref } from '@vue/composition-api'

export default defineComponent({
  setup() {
    const truckId = ref<string>('')
    const driverId = ref<string>('')

    const queryEnabled = reactive({
      driver: false,
      truck: false,
    })

Now to set the value for queryEnabled.driver to true when driverId is a string with a length longer than 3 characters we can do this:

    const queryEnabled = reactive({
      driver: computed(() => driverId.value.length >= 3),
      truck: false,
    })

This works but it also sets queryEnabled.driverto false once the string has less characters. How can we have a computed property that:

  • starts with false
  • sets the value to true once a condition is met
  • keeps the value to true once it was set before and doesn't change it back

Can this be done from within only one computed property in the reactive object? I was thinking with a function instead of a fat arrow to access this for the current computed property but can't figure it out.

like image 455
DarkLite1 Avatar asked Oct 26 '25 03:10

DarkLite1


1 Answers

You can't get access to the computed property from within itself, so use watch to update the state based on driverId:

import { watch, defineComponent, reactive, ref } from '@vue/composition-api'

export default defineComponent({
  setup() {
    const truckId = ref<string>('')
    const driverId = ref<string>('')

    const queryEnabled = reactive({
      driver: false,
      truck: false,
    })

    watch(driverId,(newVal)=>{
      if(!queryEnabled.driver && newVal.length >= 3){
        queryEnabled.driver = true
      }
    })
like image 79
Boussadjra Brahim Avatar answered Oct 27 '25 17:10

Boussadjra Brahim