What is the best way to set the `value` attribute and `v-model` attribute for a custom Vue component?

I am seeking to develop a unique Vue component that functions as a "radio div" - essentially, a div with the ability to act like a radio button where only one among multiple can be selected at a time. The div will also have a slot for including any desired content.

Typically, radio buttons in VueJS are structured as follows:

<input type="radio" name="name" value="value" v-model="variable" />

Based on this structure, I envisioned an API like this:

<div-radio name="name" value="value" v-model="variable" />

However, upon researching how to add v-model support to custom component, the first Google search result I came across suggested:

When using input elements, you can implement v-model in this manner:

<input v-model="email" />

The translation of v-model is explained as:

<input :value="email" @input="e => email = e.target.value" />

If v-model translates to :value and @input, it seems challenging to incorporate a prop named "value" alongside "v-model" simultaneously - despite the conventional functioning of VueJS radio buttons.

Could it be that I am misunderstanding the functionality of v-model? Are there alternative solutions available? Or is my desired outcome simply unattainable?

Answer â„–1

Vue offers the ability to customize the v-model's prop name and event name using the component's model option:

model

New feature in version 2.2.0

Type:

{ prop?: string, event?: string }

Details:

This feature allows a custom component to define the prop and event used with v-model. By default, the v-model on a component uses value as the prop and input as the event. However, for certain input types like checkboxes and radio buttons, using the value prop for a different purpose may be desired. Utilizing the model option can resolve any conflicts that may arise in such scenarios.

Example:

Vue.component('my-checkbox', {
  model: {
    prop: 'checked',
    event: 'change'
  },
  props: {
    // value prop is used for a different purpose
    value: String,
    // checked prop replaces the value prop for this component
    checked: {
      type: Number,
      default: 0
    }
  },
  // ...
})
<my-checkbox v-model="foo" value="some value"></my-checkbox>

The above code will result in the following:

<my-checkbox
  :checked="foo"
  @change="val => { foo = val }"
  value="some value">
</my-checkbox>

Answer â„–2

To implement v-model, you must manually manage the value and @input events:

<template>
 <div>
  <input type="radio" :name="name" :value="value" @input="$emit('input', $event)" />
 </div
</template>

<script>
 export default {
  name: 'div-radio',
  props:{
    value: Boolean,
    name: String
  }
 }
</script>

When used in a host component, simply treat it like a regular component:

...
<div-radio name="name" v-model="variable1" />
<div-radio name="name" v-model="variable2" />
... 

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

Using Jquery for a Second Timer

I have a jQuery function that looks like the one below. The result is displayed in a span, but when the page is reloaded, this span briefly disappears and then reappears. Is there a way to prevent this from happening? I need it to stay visible at all tim ...

The initial rendering of the connected component is unsuccessful due to the fact that the Redux state has not been fully

Currently, I am utilizing Redux thunk and axios to handle server requests and update the state based on the response. An issue arises when trying to render a connected component with an initial state that relies on data from the server. In this scenario, ...

The electron program is unable to locate the package.json module

I am new to electron and attempting to run an express app for the first time. However, I encountered this error: Need assistance updating code Error: Cannot find module 'C:\package.json' at Module._resolveFilename (module.js:440:15) ...

Ways to determine if a script is currently running within Node.js环境

In my Node.js script, I am importing a separate script that I want to be compatible with various JavaScript engines. Specifically, I only want the line exports.x = y; to run if the code is being executed in a Node.js environment. How can I determine this ...

Querying MongoDB in Loopback is posing a challenge

My attempt to query MongoDB from a LoopBack model is not yielding any results. This is an example of how my document appears in MongoDB: {"_id":"5b9f8bc51fbd7f248cabe742", "agentType":"Online-Shopping", "projectId":"modroid-server", "labels":["category", ...

Transferring event arguments to JavaScript in ASP.NET C# through OnClientClick

Currently, I have an asp button on my webpage. In the code behind within the Page_Load method, I am assigning some JavaScript calls in the following manner. btnExample.OnClientClicking = "functionOne(1,2);"+"function2()"; However, I am encountering a pro ...

Steps to remove a script upon clicking a button?

On my website, I have integrated a plugin called manychat using a <script>. However, when I click on the Drawer Cart, the manychat symbol overlays over the checkout button, which is not visually appealing. Is it possible to unload this script when ...

Achieving the validation with a bold red border

Hi, I'm currently learning React and I've been using regular JavaScript to validate my form. Here's a snippet of how I'm doing it: <TextField label="Title" variant="outlined" si ...

Retrieving Browser URL using Node.js

Currently, I am trying to extract the browser URL from a user who has integrated my external JavaScript file into their website. The process involves them including the JS file, which triggers an Ajax call using jQuery to communicate with my Node server. ...

Standing alone, an argument can never be fully validated without

Recently, while delving into the valuable resource titled Effective TypeScript by Dan Vanderkam, I stumbled across an intriguing scenario that left me puzzled. Within a code snippet presented in the book, there was a line - shape; that seemed perplexing ...

Attempting to integrate a complex Ruby operation (using each loop and iterator) into a JavaScript platform (such as Google Charts API) by creatively combining them in a non-conventional manner during the development phase

It's time for my application to transition into production mode, and I have come to the realization that some of the code in development mode needs a major overhaul. Particularly, the views where I embedded data iteratively into Google Charts API Java ...

Can modifications be made to a page's source content variable using Ajax?

Can modifications be made to the source content of a page through Ajax loaded by a jsp include in the main jsp? If not, is it possible to refresh only that portion of the page (the jsp that loads some of the content) and have a portion of the content in t ...

What is the best way to transfer information to a different component using Vue router?

At the moment, I have a component that is displayed on the page. When I check the this.$router variable inside this component, I notice that the full path property is '/hello/reports?report=3849534583957' and the path property is '/hello/rep ...

Is it possible to derive the language code without using the Common Locale Data Repository from a rough Unicode text

I am currently developing a dictionary application. One of the features I am working on involves identifying the language of a Unicode character when entered by a user. For example: 字 - would return ['zh', 'ja', 'ko'] ا٠...

Changing the event when a class is active in Vue3

Question I am looking for a way to trigger an event when the 'active' class is added to an element. How can I achieve this? I believe this could potentially be accomplished using a watcher method, but I am unsure how to watch for the applicatio ...

Guide on how to display registration form data on the current page as well as on a separate page

I am facing an issue with outputting registration form data to two different pages after successful validation. Specifically, I want the form data to be displayed on both the current page (form.php) and another page (profile.php). Despite my efforts to fin ...

Ways to customize a directive to show conditionally with no need for container elements

I have created a basic role-based security directive in angularjs. It's my first attempt at making a directive. My goal is to replace the following HTML: <authorize if-granted="GET_POSTS"> Hello WORLD!!!! {{name}} </authorize> with j ...

Can VueJS lifecycle hooks be outsourced?

Is it possible to organize lifecycle hooks (like created / mounted) in a separate file for better simplicity and cleanliness? MyGreatView.vue import created from 'created.js' export default { created, // created() { console.log('vue Cre ...

Is it possible to adjust the timezone settings on my GraphQL timestamp data?

I've come across a lot of helpful information regarding the usage of Date() and timezones, but something seems to be off. In my GraphQL setup (sourcing from Sanity), I have configured it to use formatString in this manner: export default function Minu ...

The Coinbase Pay application fails to compile properly due to a missing Babel loader

Currently, I am working on integrating the coinbase pay sdk into my project. Although I have successfully created a button utilizing their provided examples, I am encountering an issue during the build process which seems to be internal to their SDK. Spec ...