What is the proper way to access the current value of a computed property from within its own computation method?

Our goal is to activate a query when a string reaches a length of 3 characters or more, and keep it activated once triggered. Leveraging the Vue 2 Composition API, we have implemented a reactive object to manage the status of 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,
    })

To set queryEnabled.driver to true when driverId exceeds 3 characters in length, you can utilize this method:

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

While this approach enforces activation, it also reverts queryEnabled.driverto false if the string shortens. How can we maintain the value as true without reverting back? Is it possible to achieve this within just one computed property in the reactive object? I've contemplated using a function instead of an arrow function to access this, but have yet to find a solution.

Answer №1

To update the state based on driverId, you cannot access the computed property from within itself. Instead, utilize watch as shown below:

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
      }
    })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to find out if multiples of a specific time interval can evenly divide the time between two

I'm currently utilizing Luxon for handling dates and durations. I have two specific dates and an ISO duration, and I am looking to figure out how to determine if the interval between the dates is a multiple of the specified duration without any remain ...

Importing dynamically into Ionic 2 from locations other than the "node_modules" directory

I've recently reviewed the documentation for ModuleResolution in TypeScript on this page: https://www.typescriptlang.org/docs/handbook/module-resolution.html#node My understanding is that all files I wish to import must reside within the node_modules ...

Utilize Vue Slot with variable names for dynamic integration

My current dilemma involves a unique component called TableContainer, featuring dynamically named slots. // ... <td class="..."> <slot :name="'statuses-' + item.id" /> </td> <td class=""> ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

Having troubles with *ngFor in Angular 8? Learn how to use ng-template effectively

I need assistance creating a table with dynamically generated columns and using the PrimeNg library for the grid. Despite asking several questions, I have not received any responses. Can someone please help me achieve this? To generate table column heade ...

Executing a function for every element within a loop in Angular 11 - the Angular way

I'm currently developing a project using Angular in which users have the ability to upload multiple questions simultaneously. After adding the questions, they are displayed in a separate modal where users can include diagrams or figures for each quest ...

Would you like to learn how to display the value of a different component in this specific Angular 2 code and beyond

Hey there, I need your expertise to review this code and help me locate the issue causing variable "itemCount" to not display any value in about.component.html while everything works fine in home.component.html. I am attempting to only show "itemCount" in ...

Can you identify the reason for the hydration issue in my next.js project?

My ThreadCard.tsx component contains a LikeButton.tsx component, and the liked state of LikeButton.tsx should be unique for each logged-in user. I have successfully implemented the thread liking functionality in my app, but I encountered a hydration error, ...

Challenges with exporting dynamically generated divs using jspdf in an Angular 2 project

I have been utilizing the jspdf library to print div elements in my current project. But I recently discovered an issue where dynamic content within a div is not being printed correctly. Specifically, when incorporating simple Angular if statements, jspdf ...

What is the best way to populate empty dates within an array of objects using TypeScript or JavaScript?

I am trying to populate this object with dates from today until the next 7 days. Below is my initial object: let obj = { "sessions": [{ "date": "15-05-2021" }, { "date": "16-05-2021" }, { "date": "18-05-2021" }] } The desired ...

Discovering the automatically generated routes in Nuxtjs

Can I access the route list created by Nuxt.js based on pages folder items? The issue is that I am unsure of the exact route name generated for each component. $router.push({name: 'no-idea-what-the-route-name-is', query: { id: data.id } }) This ...

Google Chrome does not support inlined sources when it comes to source maps

Greetings to all who venture across the vast expanse of the internet! I am currently delving into the realm of typescript-code and transcending it into javascript. With the utilization of both --inlineSourceMap and --inlineSources flags, I have observed t ...

"Having trouble with a single line conditional statement not functioning properly within data in a Vue

I am facing an issue with setting the data named isVendorOrAgent in a component. It should be either false or true> based on a property that the component receives. I noticed that when I tried setting this condition within the data section of the compon ...

Encountered an issue: The type 'Usersinterface' is not meeting the document constraints

Below is a screenshot displaying an error: https://i.stack.imgur.com/VYzT1.png The code for the usersinterface is as follows: export class Usersinterface { readonly username: string; readonly password: string; } Next, here is the code for users ...

a tutorial on linking component data to a prop value

Is there a way to connect the searchString value in my Vue component to the item value in the html template it uses? I need to pass this value to the method called in my Ajax request. Vue: Vue.component('user-container-component', { props: ...

Tips for removing the error hint when focusing on input fields in VueJS

Having an issue with an error popping up when I focus on my input. Here's the code snippet: <v-text-field v-model="models.codePostal" label="Code postal" :rules="regles.codePostal" :hint="this.models.communeRe ...

How to display an HTML element conditionally with v-if based on a variable's value

Looking for a way to display a <div> element, including nested <div>s, based on the value of a variable. I'm currently using v-if, but open to better suggestions. I attempted wrapping the entire <div> in a <template v-if> as s ...

How do you define prop types when passing them in Nextjs?

Welcome to my page import { InferGetServerSidePropsType, GetServerSideProps } from 'next' import ProductList from '../../component/product/ProductList' export interface Item { title: string price: number } const products ...

Finding the imported function in Jest Enzyme's mount() seems impossible

I'm currently facing an issue where I need to mount a component that utilizes a function from a library. This particular function is utilized within the componentDidMount lifecycle method. Here's a simplified version of what my code looks like: ...

What is the best way to specify the return type in TypeScript when there is a possibility of multiple types?

I'm currently working on implementing type definitions for an Axios API client but I’m struggling with indicating to the compiler the specific return type that I am expecting. Here is a simplified example: import axios, { AxiosResponse } from "axi ...