Guide on inputting Vue component in props

<template>
  <v-dialog
    width="auto"
    v-model="isShown"
    transition="dialog-bottom-transition"
  >
    <v-card>
      <v-card-title v-if="title"> {{ title }}</v-card-title>
      <v-card-text>
        <component v-if="checkText()" :is="text"></component>
        <span v-else>{{ text }}</span>
      </v-card-text>
      <v-divider></v-divider>
      <v-card-actions>
        //
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import { defineProps, computed } from "vue";

const params = defineProps<{
  show: boolean;
  title?: string;
  text: string | object;
  confirmButtonText?: string;
  closeButtonText: string;
}>();
const emit = defineEmits(["closeWindow", "confirmOperation"]);

const isShown = computed({
  get() {
    return params.show;
  },
  set(newValue) {
    emit("closeWindow");
  },
});

function checkText() {
  return typeof params.text !== "string";
}
</script>

I am looking for a way to correctly type the prop "text" in my reusable modal window component. I currently use an object and it works, but I want to implement strong typing for better code quality. Note that v-dialog, v-card, etc., are components from Vuetify library.

Answer №1

To kick things off, you can begin by crafting a component and displaying it with Vue's h function:

import { defineComponent } from 'vue'
const CustomComponent = defineComponent({
  name: 'CustomComponent',
  props: {
    value: {
      type: [String, Number, Object] as PropType<string | number | VNode | Component>,
      default: '',
    },
  },
  setup(props) {
    return () => {
      if (typeof props.value === 'string' || typeof props.value === 'number')
        return props.value
      return props.value ? h(props.value) : null
    }
  },
})

To utilize this component, simply follow these instructions:

<template>
  <CustomComponent :value="text" />
</template>

<script setup>
import { Component, VNode } from 'vue'
const props = defineProps<{
  text?: Component | number | string
}>()
</script>

This piece of code is available in @unoverlays/vue, allowing you to easily install @unoverlays/vue and start using it:

pnpm i @unoverlays/vue
<template>
  <CustomComponent :value="text" />
</template>

<script setup>
import { CustomComponent } from '@unoverlays/vue'
import { Component, VNode } from 'vue'
const props = defineProps<{
  text?: string | number | VNode | Component
}>()
</script>

If you need to validate props, make use of the validator for props.

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

Issue with SvelteKit: PageData not being refreshed in API response after initial render

I am relatively new to working with Svelte and SvelteKit, and I am currently trying to fetch data from an API. I have followed the SvelteKit todo sample code, which works well for the initial rendering and when clicking on an a tag. However, I am facing an ...

What is the most effective way to showcase a list of image URLs in HTML with Vue?

Currently, I am working with an array called thumbnails that holds the paths to various images. My goal is to use masonry in Vue to arrange these images in a grid format, but I'm encountering some difficulties achieving the desired outcome. This is m ...

What is the reason behind typescript not needing `undefined` with the ?: operator on arrays?

type Artifact = { a:string } const items : Artifact[] = []; // this will result in a syntax error let z?: Artifact; // assigning undefined to a variable of type Artifact is an error const b : Artifact = undefined; // despite expectations, this assi ...

When working with Vue, setting the default value for props as a computed property is an

props: { rules: { type: Array, required: false, default: () => [ (file) => !file || file.size < 10000000 || this.getJsonDataByLocale.less_than_10mb_message, (file) ...

Showcasing an array in VueJS sourced from a JSON file with NodeJS

Currently, I am dealing with a JSON file that contains the following data: { "manufacturers": ["Sony", "Microsoft", "Nintendo", "Kita"] } In my NodeJS application, I retrieve this data as shown below: let uploadrawdata = fs.readFileSync('./conf ...

Displaying data from nested arrays using Vue.js, Axios, and API calls in the

Extracting data from an API with the following structure - Array ( [lastUpdate] => 1571616000 [lanuage] => en [data] => Array ( [0] => Array ( [itemId] => 1e3ac1f-6f1ddb0-5 ...

Discover the ways to reach the router in Nuxt outside of the Vue component scope

When working with Nuxt.js, I have a helper function that needs to be able to navigate the router programmatically. In Vue.js, I would typically achieve this by importing the router using `import router from "@/router"`. However, how can I accomplish this m ...

How can you determine the number of times a particular digit appears around a specific position in a TypeScript array

(Utilizing Typescript for assistance) I am looking to determine the number of occurrences of the digit 2 surrounding a specific position within an array. The function takes in the position coordinates as parameters - param 1 for row and param 2 for column. ...

Tips for automatically closing the Toggle Navigation feature in Vue JS when a user clicks outside of the navigation container

Is there a way to close the toggled navigation menu automatically when the user clicks outside of the navigation container? I have implemented two ul menus inside the navigation menu and would like the subNavActive, safNavAcitve, and repNavUl variables to ...

Avoid These Mistakes When Combining Link URLs in VueJS

I'm embarking on a new project and I'm faced with an issue regarding rendering a list of links. The URLs of my links are stored in a table in the format of "www.sitename.com". They display correctly initially, but upon clicking on one of them, in ...

Tips for attaching inline styles to the body element with a vuejs component

I am new to vue.js and have been learning for a couple of days now. There are still some concepts that I am struggling to understand. I am currently working on creating a dropdown menu that appears when the user clicks on three dots. However, I am facing a ...

Creating: A Pair of Vue Components with Matching Sass Styles

As I ponder on the best way to structure my Vue components, I am faced with a dilemma. Two of my Vue components share the same sass code, yet they have different markup, state, and methods. I am seeking a solution to reduce repetition of sass code across t ...

"Utilizing Vue.js for Managing Foreign Keys in Database Entries

I am currently utilizing input in Vue.js. The structure of this input is as follows: induk_id:'', nama_barang:'', qtt:'', satuan:'', har ...

As I work on creating a jest snapshot test, I've encountered an issue with TypeScript error while using Redux within the component

Hi, I'm currently working on snapshot testing in Jest with TypeScript and React.js. The component is fetching state from the Redux store, so I've set up a mock store with all the initial states provided. However, the test is failing and the error ...

Retrieve HTML content from Vuetify components without displaying it on the webpage

I have a project where I need to retrieve the HTML code from various Vuetify components. Instead of just as a HTML string, I actually need it as a DOM element that can be easily added to the body. This is necessary for me to be able to utilize these compon ...

What causes the mounted hook in Vue to be triggered multiple times when used within a plugin or mixin?

How can I prevent repetitive behavior in my code? Is this a bug that needs fixing? Take a look at the plugin below: const globala = { install(Vue) { Vue.mixin({ mounted() { console.log('hi') } }) } } And here&apos ...

TypeORM: When generating a migration, a SyntaxError is thrown stating that an import statement cannot be used outside a

While configuring TypeORM in my NextJS TypeScript project, I encountered an issue where I received the error message: SyntaxError: Cannot use import statement outside a module when attempting to create migrations for my entities. ...

Implementing data binding with JSON objects in Vue.js

I recently used the Vuetify component to create a todo app using Vue.js with Firebase as the database. I am currently struggling with binding the title from a JSON object. Can anyone help me with how to bind a specific value or attribute from an object? ...

Tips for notifying the user about incorrect login credentials in Ionic 3

I'm attempting to implement a notification system using showAlert to inform users when they enter an incorrect email or password, but I'm having difficulty achieving this using try and catch statements Would it be feasible for me to use try and ...

Tips for utilizing interpolation for conditions instead of using *ngIf

For my application, I am using two different languages and have written them within two <option> tags. Is it possible to combine both conditions into a single <option> tag using interpolation? <option *ngIf="this.language=='en&apos ...