Using Vue JS to set a default value in a custom radio group

Recently, I attempted to implement a default value in a custom radio component that I developed.

Below is the code snippet:

<template>
<div class="custom-radio-button">
  {{value}}
  <div  v-for= "item in localValue">
    <input type="radio" :value="item.value" name=item.name @click=onSelected(item.value) >
    <span>{{item.label}}</span>
    </input>
    </div>

</div>

<script>
  import Vue from 'vue'

  const name = 'CustomRadioButton'

  export default {
    name,
    componentName: name,

    props: [ 'name', 'value', 'isDefault', 'label'],


    data() {
      return { 
        localName: this.name,
        localValue: this.value
      }
    },
    methods: {
      onSelected (value) {
        this.$emit('clicked', value)
      }
    }
  }
</script>

I used the component as shown below:

<CustomRadioButton :value=RadioFieldData  @clicked="isRadioButtonSelection" isDefault='yellow'></CustomRadioButton>

Here is the accompanying JSON data:

RadioFieldData:[
  {label:'Fire', value:'red', name:'colour' },
  {label:'Sun', value:'yellow', name:'colour',isDefault:'yellow'},
  {label:'Water', value:'blue', name:'colour'}
]

My query revolves around the best approach for passing the value "yellow" to the radio button group. Suggestions?

Answer №1

The issue you're facing is that props must be in kebab-case format when used in your template. To set isDefault to "yellow," you should use

is-default="yellow"

Refer to https://v2.vuejs.org/v2/guide/components.html#camelCase-vs-kebab-case for more details.

Once you are able to correctly read that property, you can utilize

:checked="item.value == isDefault"

Here's an example.

Vue.component('custom-radio-button', {
  template: '<div class="custom-radio-button">
  Default: {{isDefault}}
  <div v-for="item in value">
    <input type="radio" :value="item.value" name="item.name" @click="onSelected(item.value)" :checked="item.value == isDefault" />
    <span>{{item.label}}</span>
  </div></div>',
  props: ['value', 'isDefault'],
  methods: {
    onSelected(value) {
      this.$emit('clicked', value)
    }
  }
})

new Vue({
  el: '#app',
  methods: {
    isRadioButtonSelection (val) {
      console.log('isRadioButtonSelection', val)
    }
  },
  data: {
    RadioFieldData: [{"label":"Fire","value":"red","name":"colour"},{"label":"Sun","value":"yellow","name":"colour","isDefault":"yellow"},{"label":"Water","value":"blue","name":"colour"}]
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
  <custom-radio-button :value="RadioFieldData" 
                       @clicked="isRadioButtonSelection"
                       is-default="yellow">
  </custom-radio-button>
</div>

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

"Encountering an issue with the parameter 'undefined' in the .find()

Recently, I've been facing some challenges while using the .find() method within a vuex getter. I initialized a store with a list under state (pages) // state.js const state = { pages: [{id:1, content:"Page 1"}, {id:2, content:"Page 2"}] }; In my ...

Updating a component in Angular 4.3.1 from within an observable callback

My Project Journey I am currently immersing myself in learning Angular by working on a personal project: developing a game that involves routing, services, and more. One of the requirements is to hide the header on the landing page (route for '/&apos ...

Striped artifacts can be observed in the lights of A-Frame technology, with their appearance varying depending

I'm currently using A-Frame version 1.0.4 and have experimented with both spotlights (as shown in the attached image) and direct light sources. Adjusting the shadowBias to -0.0001 only minimally impacts the artifact issue. By setting shadowMapHeight ...

Is there a way to efficiently fetch localStorage data upon launching a React application and seamlessly store it in Redux using the useEffect hook without experiencing any data loss issues?

Should I avoid mixing React hooks and mapStateToProps in my application and instead use Redux hooks like useSelector? In my React app, I have an array of 'friend' data stored in Redux. Using useEffect in one of my components, I am saving this da ...

JAVASCRIPT ENCOUNTERS ISSUE WITH RANDOM TEXT GENERATION

Utilizing an array of words, we are in the process of generating random text. The goal is to shuffle and combine these words to form new "random sentences". However, we have encountered a minor issue - the addition of "undefined" at the beginning of each p ...

Utilizing the svg component in vuejs

As a React developer, I am currently working on a project using Vue.js. In React, we typically use SVG images as components. How can I achieve something similar with Vue.js components? If anyone has experience with this, could you please suggest a solution ...

I'm having trouble getting my .click method to work with the <div id=menuButton>. Can anyone help me figure out why this is happening?

Here is the HTML code I created for a dropdown menu. Initially, in the CSS file, the menu is set to display: none; <!doctype html> <html> <head> <title>DropDown Menu</title> <link rel="stylesheet" href="normalize ...

Implement Clip Function with Gradient Effect in JavaScript on Canvas

Trying to incorporate the clip() function within the canvas element to create a unique effect, similar to the one shown in the image. I have successfully achieved a circular clip, but I am now aiming for a gradient effect as seen in the example. How can th ...

Discover the secret to instantly displaying comments after submission without refreshing the page in VueJS

Is there a way to display the comment instantly after clicking on the submit button, without having to refresh the page? Currently, the comment is saved to the database but only appears after refreshing. I'm looking for a solution or syntax that can h ...

Utilizing JavaScript's Facebook Connect feature on a Ruby on Rails website

My ruby-on-rails web application is in need of integrating "Facebook connect" functionality to enable users to share various activities on Facebook. Are there any Javascript methods I can use for this purpose? Any demos you can suggest? In addition, I wou ...

Upon refreshing, the page displays a message stating that the resource being sought has been removed, its name has been altered, or it is currently inaccessible

For my project, I decided to deploy a Nuxt 3 website as a classic SPA without the need for SSR. I used nuxt generate and deployed the contents from .output/public/ in an Azure static web app. Everything is up and running smoothly, but I encountered an issu ...

What is the best way to iterate through data within a view while showcasing information retrieved using AngularJS?

As I start my journey into learning AngularJS, I am looking for some guidance from those who have experience with it. Although I am proficient in JavaScript/jQuery, I am finding it challenging to grasp the fundamentals of AngularJS at the moment. My query ...

What is the best way to display multiple VR scenes on a single webpage?

Currently, I am attempting to display several 360 photos utilizing the a-frame library through implementing a-scene. However, I am encountering an issue where only one scene is being rendered on my page. Are there any alternative approaches to address this ...

Integrate third-party code into your Angular application

I've been working on an Angular project and I wanted to spice things up by adding a confetti animation. I found this cool animation that I'd like to incorporate into my project: http://jsfiddle.net/vxP5q/61/?utm_source=website&utm_medium=emb ...

Switch the style of a set of thumbnail images when clicked

I am working with a set of thumbnails where one has an "p7_current" class applied, giving it a border, while the rest have an "p7_inactive" class removing the border. My goal is to have the last clicked thumbnail in a group of 6 to have the "p7_current" c ...

Transferring user-selected values from JavaScript to a PHP file

When sending values from JavaScript to a PHP file, everything works smoothly when all the values are collected. Step1 functions perfectly as both fields are mandatory. However, in Step2, values are only sent when all the fields are selected. There are co ...

Best practice for detecting external modifications to an ngModel within a directive

I've been working on creating a directive that can take input from two sources and merge them into one. To achieve this, I'm monitoring changes in both inputs and updating the combined value in the ngModel of my directive. However, there's ...

res.json responding with altered input unexpectedly

When I use my res.json function, it seems to be altering my data. The data appears correct when logged in the function, but changes inside res.json and I can't figure out why. For example, instead of returning {"unix":"1484600306","naturalFormat":"20 ...

Building intricate hierarchical menus with Material-UI 4.9

I am currently incorporating the @material-ui/core library into my application and aiming to implement a nested menu feature. I have referred to the material.io specification which discusses nested menus, but unfortunately, the material-ui library does not ...

Revamp the Twitter button parameters or alter its settings

I'm working on a web page that includes a Twitter button. Before the button, there is an input field and a form where users can easily add relevant hashtags for the page. The goal is to take the text from the input field and populate it in the Twitter ...