Tips for sending a dynamic ref to a computed property using the Composition API

I'm working on creating a single computed property that can dynamically match two reactive variables. My tech stack includes Typescript, Vue3-Composition API, and PrimeVue.

Within Prime Vue, I have two similar MultiSelect components structured like this:

<MultiSelect
  v-model="selectedClients"
  :selected-items-label="itemsSelected"
  :options="clientsList"
  option-label="firstName"
  option-value="id"
/>

<MultiSelect
  v-model="selectedCars"
  :selected-items-label="itemsSelected"
  :options="carsList"
  option-label="carType"
  option-value="id"
/>

My goal is to bind the selected-items-label attribute to a computed property called itemsSelected, like so:

const itemsSelected = computed((selector) => {
  return selector.value.length > 1 ? "{0} items selected" : "{0} item selected";
});

I am aware that I could use separate computed properties by toggling between selectedClients and selectedCars, but this feels redundant.

const accountsItemsSelected = computed(() => {
  return selectedClients.value.length > 1
    ? "{0} items selected"
    : "{0} item selected";
}); 

Is it possible to pass a dynamic parameter to a computed property in order to achieve this functionality with just one computed prop?

Answer №1

You have the option to utilize a higher order function:

const counter = computed(
  () =>
    ({ length }) =>
      `${length || 'No'} item${length === 1 ? '' : 's'} selected`
)

Application:

<MultiSelect
  v-model="selectedClients"
  :selected-items-label="counter(selectedClients)"
  :options="clientsList"
  option-label="firstName"
  option-value="id"
/>
<MultiSelect
  v-model="selectedCars"
  :selected-items-label="counter(selectedCars)"
  :options="carsList"
  option-label="carType"
  option-value="id"
/>

Demo.

Note: The reference provided in the example must always have a value with .length (an array or a string).

If it becomes falsey (false, null, undefined, etc...), an error will occur.
To allow for falsey values, adjust it to:

const counter = computed(
  () => (r) => `${r?.length || 'No'} item${r?.length === 1 ? '' : 's'} selected`
)

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

Implementing functionality to assign a single button to multiple div elements in TypeScript and control their behavior individually upon clicking

One of my tasks is to create an expand/collapse button and assign it to different divs. Below you can find the code I've been working on: let expandButtonHTML = require("!text-loader!./button.html"); ... let expandButton = frame.contents().find(".exp ...

The ion-col with col-3 is causing a template parse error

Currently, I am facing an issue while trying to print data from a constructor. Everything is working fine until I added col-3 to ion-col. It seems like I missed including some module, but I am not sure which one. This is my home.ts file: import { Compone ...

Utilizing Typescript to filter a table and generate a transformed output for each item

What's the best way to return each mapped element of an array using an optimized approach like this: this.itemsList= res.map( ( x, index ) => { x.id = x.code; x.itemName = x.name; return x; }); I've tried optimizing it with a second me ...

Identifying Shifts in Objects Using Angular 5

Is there a way to detect changes in an object connected to a large form? My goal is to display save/cancel buttons at the bottom of the page whenever a user makes changes to the input. One approach I considered was creating a copy of the object and using ...

I keep receiving error code TS2339, stating that property 'total' is not recognized within type any[]

Check out this code snippet. Can you provide some assistance? responseArray: any[] = []; proResponseArray: any[] = []; clearArray(res: any[]): void {res.length = 0; this.response.total = 0; } handleSubmit(searchForm: FormGroup) { this.sho ...

Using TypeScript to type styled-system props

Currently, I am utilizing styled-system and one of the main features of this library is its shorthand props that allow for simple and quick theming. Although I have streamlined my component, a significant aspect lies here: import React from 'react&a ...

What is the best ECMAScript version to select for implementing the TypeScript compiler in an Electron application?

In my Electron 5.0.6 project, I currently have es3 as the default target in my tsconfig.json file. However, I received an error message indicating that I need to upgrade to at least es6 to utilize getter/setter functionality in TypeScript. I am now contem ...

The "main" entry for ts-node is not valid when running ts-node-dev

Recently, I embarked on a TypeScript project using yarn where I executed the following commands: yarn init -y yarn add typescript -D yarn tsc --init yarn add ts-node-dev -D Subsequently, I crafted a script titled dev that triggers tsnd src/index.ts, howev ...

Having difficulty updating the value of a FieldArray with setFieldValue in Formik

Thank you for taking the time to read this. I am currently working on creating a form using Formik that involves nesting a FieldArray within another FieldArray. Oddly enough, setFieldValue seems to be functioning correctly as I can log the correct values ...

What is the error message "Cannot assign type 'IArguments' to argument"?

Currently employing a workaround that is unfortunately necessary. I have to suppress specific console errors that are essentially harmless. export const removeConsoleErrors = () => { const cloneConsoleError = console.error; const suppressedWarnings ...

The Order ID field in the Serenity-Platform's Order Details tab is not registering orders

I've been working on replicating the functionality of Orders-Order detail in my own project. https://i.stack.imgur.com/Bt47B.png My custom module is called Contract and Contract Line item, which I'm using to achieve this. https://i.stack.imgur ...

The process of declaring a nullable callback variable in TypeScript

Can the declaration of the resolve variable in the TypeScript code below be simplified while maintaining type safety? I am new to TypeScript, so please bear with me. The objective is to store the promise resolver callback that is passed to the executor fu ...

Suggestions for efficiently filtering nested objects with multiple levels in RXJS within an Angular environment?

Just a Quick Query: Excuse me, I am new to Typescipt & RxJS. I have this JSON data: [ { "ID": "", "UEN": "", "Name": "", "Address": "", "Telephone&quo ...

Ways to access UserProfile in a different Dialogio

For the implementation of a chatbot, I am utilizing Microsoft's Bot Builder framework. However, upon implementing an alternative path to the dialog flow, I noticed that the user's Profile references are getting lost. Here is the code snippet fr ...

An Uncaught Error has occurred: The module titled "functions" has not been loaded within the current context _. To resolve this issue, please make sure to use

I've been grappling with setting up TypeScript in my ASP.NET Core project without much success. Initially, I managed to implement a basic functionality where an alert pops up when the page loads successfully. My next challenge was to manually conver ...

Vue3 with Typescript encounters an issue when attempting to apply v-model to a textarea element

Trying to implement v-model on a tag within my Vue component, I encountered the following error that is puzzling me: The 'textInput' property does not exist on the type '{ $: ComponentInternalInstance; $data: {}; $props: Partial<{}> ...

Utilizing the map function to incorporate numerous elements into the state

I'm struggling with 2 buttons, Single Component and Multiple Component. Upon clicking Multiple Component, my expectation is for it to add 3 components, but instead, it only adds 1. import React, { useState, useEffect } from "react"; import ...

How can I display images stored locally within a JSON file in a React Native application?

Hey everyone, I'm currently facing an issue with linking a local image from my images folder within my JSON data. Despite trying various methods, it doesn't seem to be working as expected. [ { "id": 1, "author": "Virginia Woolf", " ...

Error encountered while running npm build: Typescript issue within plotly.js/index.d.ts

Trying to implement this code snippet: import createPlotlyComponent from 'react-plotly.js/factory'; const Plot = createPlotlyComponent(window.Plotly); https://i.sstatic.net/2rI0a.png in my React project implemented in TypeScript. Encountered a ...

Typescript threw an error: Zod was anticipating a string, but instead it got

I am encountering a Zod error multiple times while attempting to submit my req.body data to the Prisma ORM using Insomnia: ZodError: [ { "code": "invalid_type", "expected": "string", "received" ...