Can a Vue component be designed to have one required prop out of several options?

I am currently developing a Vue component that is required to accept either text input or a link. When a link is provided, an anchor tag needs to be created and when text is inputted, a span should be generated. The issue I am facing is that it seems each Vue prop has its own validator, as seen in the following code:

    url: {
      type: String,
      required: true
    },
    text: {
      type: String
    }

The above code does not meet my requirements because it mandates the presence of url even if only text is passed.

How can I modify the component so that it can accept either a url or text as mandatory input?

Additionally, how can I ensure the component only accepts one type of input, failing if both URL and text are provided?

Answer №1

It is important that prop validators are pure functions as they do not have access to the THIS of the component. However, you can overcome this issue by utilizing a single prop with type Object:

props:
{
  params:
  {
    type: Object,
    validator: (value) =>
    {
      return !!value &&
        Object.keys(value).length === 1 &&
        ['url', 'text'].includes(Object.keys) &&
        typeof Object.values(value)[0] === 'string' &&
        Object.values(value)[0] !== '';
    }
  }
}

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 trigger a JavaScript function whenever a field reaches a specific length?

I need to update a function that currently triggers when the user clicks or tabs out of the employee_number field. My goal is for it to run whenever the length of the entered numbers reaches 6, without requiring the user to leave the field. When I attempte ...

The $mdDialog component from Angular Material fails to display again after being hidden once

There seems to be an issue with my app's chat button functionality. When the chat button is clicked, it opens an $mdDialog. The problem arises when I use $mdDialog.hide() to close the dialog window after clicking on a user name within the dialog. Subs ...

Error: The method being called on this.props is not recognized as a valid function

I'm encountering an error in my code TypeError: this.props.* is not a function I've been trying to troubleshoot it but so far I haven't been able to identify what's causing the issue. I've attempted different methods, includin ...

Retrieve the current time of day based on the user's timezone

Currently, I am working with a firebase cloud function that is responsible for sending push notifications to my app. My main requirement is to send notifications only during the day time. To achieve this, I have integrated moment-timezone library into my p ...

How can I combine addClass with fadeIn/fadeOut in JavaScript?

Can the addClass and fadeIn functions be combined in JS? Although I'm not very experienced with JS, I'm working on a script where the div container changes background color by fading in and out on text hover. I've created a CodePen to demo ...

Error: Phonegap displaying incomplete or corrupted image

Currently, my Android application is being developed with Phonegap. Users have the ability to take photos that are then stored in a mysql database (medium-blob column) using a simple INSERT INTO query without altering the data. These images are then sent s ...

The Owl carousel displaying in various boxes, each with their own unique showcase

I need to have multiple owl carousels on my website. The issue is that I want one carousel box to display only one item at a time, while another box should display three items at once. How can I target each carousel to make these distinctions? Take a loo ...

The problem with the Image Gallery carousel not functioning properly in a right-to-left direction arises when attempting to modify

I have been developing an image gallery that functions perfectly in the English version of the website. Now, I am tasked with replicating the same functionality for another version of the website that requires right-to-left (RTL) direction. However, when I ...

Using a prop array as v-model in a Vue JS CheckBoxGroup implementation

Struggling to create a reusable CheckBoxGroup component with a prop array as v-model. I checked out the vuejs guide at https://v2.vuejs.org/v2/guide/forms.html#Checkbox which uses the v-model array in the data of the same component. However, this approach ...

Adjust THREE.PerspectiveCamera's distance without altering its viewing orientation

I have a PerspectiveCamera in THREE.js positioned somewhere in space as a child of a mesh. The camera is currently looking at the mesh with local coordinates [0, 0, 0]. I am looking for a way to change the distance of the camera from the mesh without chang ...

Ending a session in JavaScript using session_destroy()

I am seeking a JavaScript code that can automatically end the session of inactive users on a live chat website. The website tracks user activity every 5 minutes and updates the database with a timestamp of their last activity. For example, if a user has n ...

changing button text in ajax upon successful completion

I am looking to update the button text upon successful completion. Specifically, I would like to change it to "accepted" after a successful response. <button type="button" onclick="saveData<?php echo $row1->id; ?>()">Accept</button> ...

Facing difficulty updating a collection in MongoDB using Mongoose and JavaScript

This is the database schema I am working with let couponId = Schema({ RestaurantId: { type: String }, RestaurantName: { type: String }, RestaurantLocation: { type: String }, AssignedTo: Schema.Types.Mixed, CouponValue: { type: [Strin ...

When activated, the Chrome extension runs automatically instead of waiting to be clicked

Below is the content of my manifest.json file: { "manifest_version": 2, "name": "PageEscape", "version": "1.0", "description": "", "background": { "scripts": ["background.js"] }, "browser_action": { "defau ...

An issue with Laravel 5.5 and its bootstrap functionality

I encountered the following error: Uncaught Error: Bootstrap's JavaScript requires jQuery. jQuery must be included before Bootstrap's JavaScript. app.js require('./bootstrap'); window.Vue = require('vue'); import Vue f ...

conditional statement for manipulating data in javascript/html

I am working on appending results in an object as options in a datalist dropdown. While it is functioning correctly, the issue arises when not all elements have a specific level in the object consistently, impacting which results are added to the list. $( ...

How to extract component prop types in Vue 3 with typescript for reusability in other parts of your application

When you specify the props under the "props:" key of a Vue component, Vue can already automatically determine their types, which is quite convenient. However, I am wondering if there is an utility type in Vue that can be used to extract the props' ty ...

What is the process for creating URL query parameters?

What is the process for generating parameters after node?_=xxxxxx? If I am using a Python script to access the URL, how can I retrieve these parameters? edit: I apologize for not providing enough information. This is my first post as a novice. I am atte ...

Trigger Vue to pass a reference of a different element when clicked

Hello, I'm looking to retrieve an element by its class name or some other method. Specifically, I want to target an element with the class name "nav" when a menu item is clicked within my code. I've tried using refs but can't seem to get it ...

What is the best way to show search suggestions on Google Maps autocomplete once three characters have been entered?

While integrating google-maps into my react app, I encountered an issue with the autocomplete feature. I would like the location search to display options only when at least 3 keys are entered, but Google maps autocomplete starts showing options with jus ...