Exploring the utilization of properties within the composition API

Can props be shared between components using the composition API, or is it still necessary to use mixins for that purpose?

For instance, if I have a "visible" prop that I want to reuse in 5 components, how can I define it once and reuse it efficiently with the composition API?

Instead of resorting to mixins like before, here's what I would usually do:

const mixin = {
   props: { visible: { type: Boolean, required: false } }
}

To use this mixin in a component:

mixins: [theMixinAbove]

Is there a way to achieve this same functionality using the composition API?

Answer №1

If you want to achieve this, consider incorporating props in a similar way. Keep in mind that setting it up during the initialization is not possible as the props are already expected at that point.

One approach is to define a function within your setup logic and then destructure it along with the rest of your props like so:

props:{myInternalProp:String, ...withVisibilityProps()},

const app = Vue.createApp({})

app.component('my-component', {
  template: '<h1>My Component is {{visiblity}}</h1>',
  props:{...withVisibilityProps()},
  setup(props){
    return({...withVisibility(props)})
  }
})

function withVisibility(props) {
  return {visiblity:Vue.ref(props.visible?"visible":"not visible")};
}
function withVisibilityProps() {
    return {visible:Boolean};
}

app.mount('#app')
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4533302005766b756b71">[email protected]</a>/dist/vue.global.prod.js"></script>
<div id="app">
  <my-component :visible="true"></my-component>
  <my-component :visible="false"></my-component>
</div>

It's important to note that the setup function manages the visibility variable. If you only require the prop, you can omit the withVisibility and setup sections.

Answer №2

One approach is to implement script setup and employ defineProps within the composable function. Learn more here

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

Converting a JavaScript IIFE library into a React Component

Hello, I am currently in the process of learning React JS and there are two JavaScript files that I am working on: Polyfill.js -> hosted on github CustomNavbar.js -> created by me Here is the structure of polyfill.js: export default (function(win ...

What's the best way to invoke a function from a different JS file or create a custom event in JQuery that includes a parameter as a data object?

I am facing an issue while using requireJS to call a function from a required JS file. In my main app.js "controller", I have included (plugin)app.js, which contains all plugin configurations and related functions. The snippet below is from app.js defin ...

Tips for including parameters in an array of values when using getStaticPaths

I'm trying to retrieve the slug value that corresponds with each number in the getStaticPaths for my page structure: /read/[slug]/[number]. The code I have is as follows: export async function getStaticPaths() { const slugs = await client.fetch( ...

Javascript problem involving multiple scopes in closures

What is the most effective solution for addressing this issue related to closure in JavaScript? Here is a simple problem I am facing: I have 10 spans with onclick events (I want an alert showing the number of the span clicked on each click): var spans = ...

Progress to the following pages after each page remains inactive for 3 seconds

Is it possible for someone to assist me in creating a script that automatically switches between pages when the page is idle for 3 seconds? My current setup only allows for movement from one page to another, but I have 4 pages that I would like this featur ...

Verifying the existing user in a personalized Ajax form that is used to update a Woocommerce order

Currently, I am developing a form that allows users to update specific order details, such as expenses and the reason for the expense. After updating the order, a JavaScript alert confirms the successful update, and the order's metadata is updated acc ...

Input field for postal code containing only numbers (maximum 5 digits) in Angular version 4/5

I am struggling with creating an input field that accepts numbers. If I use type="text", I can only type 5 characters of alphanumeric data, but if I use type="number", it allows any number input without limiting it to just 5 numbers. Thank you in advance f ...

JQuery Datatables: Struggling to make JQuery function work following AJAX update

Watch this screencast to get a clearer understanding of the issue.... I'm currently working on my first project involving AJAX, and I'm encountering some obstacles. The datatable is loading user details from a JSON output using AJAX. Each row ...

Having trouble with executing functions on an express js Route?

I'm currently exploring Node and Express, and I'm encountering an issue when trying to pass a function instead of plain text on my route. It seems that the documentation only mentions using res.send() method with text. Even when attempting to use ...

Activate the Sass IntelliSense feature specifically for .vue files within the VS Code editor

Could IntelliSense for Sass be activated in .vue documents without connecting them to sass, as this may disrupt other extensions dependent on the .vue file association? ...

Error in ReactJs production code: ReferenceError - the process is undefined

Having some trouble with my ReactJs production code not recognizing environment variables. The error message reads: Uncaught ReferenceError: process is not defined <anonymous> webpack://testProject/./src/agent.js?:9 js http://localhost:8080/s ...

Navigating JSON encoded strings with jQuery

Currently, I am utilizing Django to create JSON encoded objects that are then retrieved using jQuery.getJSON(). The standard simplejson encoder encodes strings following the JSON "standard". For example, any string containing a '/' is converted t ...

What is the best way to assign a series of radio buttons to an array within an Angular controller's model?

Let's say I have a controller that contains an array property named 'houses'. I want to use ng-repeat to display this array on a table row with a set of radio buttons (true/false, etc.). How can I ensure that selecting any of these radio but ...

Enclose each instance of "Rs." with <span class="someClass">

I'm facing an issue with the currency symbol "Rs." appearing in multiple places on my website. I want to enclose every instance of this text within <span class="WebRupee">. However, if it's already wrapped in <span class="WebRupee">, ...

Locate a button element and dynamically assign an identifier using jQuery or JavaScript

I am currently working on a webpage that contains two forms, both enclosed within a <DL> element. <dl> <form action="" method="POST" style="display:inline-block;"> <dl><dt></dt><dd><input class="submit" typ ...

Combining the power of Google Blockly with AngularJS

I am looking for a way to empower advanced users to create and save custom math formulas that will be used in a shopping cart check-out process. These users are not programmers, but can follow instructions easily. The formulas should be editable by the use ...

Creating a Graph using VueJS

I am currently working on creating a graph using data from an API and visualizing it on a graph. I found this example of a Force-Directed Graph (https://bl.ocks.org/mbostock/4062045) which is really helpful. However, I am curious to know if there is a mor ...

Is it possible to dynamically adjust div height using on resize event?

In my current setup, I have two separate divs on the left and right sides. The issue arises when the height of the left div exceeds the height of the right div. In such cases, the function adjusts the heights to be equal and hides any excess text in the le ...

Tips for applying and removing classes using an anchor tag

When I click on an anchor, I want it to add a specific class. This is my current markup: <ul> <li> <a href="<?php echo base_url()?>home/promos/call" class="promo-call"></a> </li> ...

Can anyone explain why the animation doesn't work when deleting a div?

Using vue.js 2.9 in my current project, I have set up animations for transitions and translations: transform: translate3d(0, 0, 0) &.move-enter-active, &.move-leave-active transition: all 0.2s linear &.move-enter, &.move-leave transfor ...