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:
falsetrue once a condition is mettrue once it was set before and doesn't change it backCan 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.
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
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With