Sending Data from Clicked Button to Another Component as a Prop

I am struggling to figure out how to pass a value that is set inside a button to a child component. Essentially, I want the value of the clicked button that displays a percentage to be passed as a prop value. This prop value should update depending on which button I click. Do I need to utilize a v-model? If so, how can I achieve this? Below is my current progress...

ButtonGroup.vue

<button class="button" v-on:click="percentageValue(0.05)">5%</button>
<button class="button" v-on:click="percentageValue(.10)">10%</button>
<button class="button" v-on:click="percentageValue(.15)">15%</button>
<button class="button" v-on:click="percentageValue(.25)">25%</button>
<button class="button" v-on:click="percentageValue(.50)">50%</button>
<script>
  export default {
    name: 'ButtonGroup',
    data(){
      return{
        percentage: null
      }
    },
     methods:{
      percentageValue(value){
         this.percentage = value;
      }
    },
    props:['percentage']
  }
</script>

Calculator.vue

<ButtonGroup :percentage="percentage"/>

Answer №1

Here is an alternative solution:

Vue.component('option-group', {
  template: `
  <div class="options">
    <ul>
      <li v-for="(item, index) in items" :key="index">
        <button class="btn" 
                @click="selectItem(item)"
                :class="selectedItem === item && 'active'">
          {{ item }}
        </button>
      </li>
    </ul>
  </div>
  `,
  props:['list'],
  data(){
    return{
      selectedItem:  this.list[0],
      items: [5, 10, 15, 25, 50 ]
    }
  },
  methods:{
    selectItem(val){
      this.selectedItem = val;
      this.$emit('item-selected', val);
    }
  },
})

new Vue({
  el: '#example',
  data() {
    return {
      selectedOption: 5
    }
  },
  methods: {
    itemSelected(value) {
      this.selectedOption = value
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
ul {
  list-style: none;
  display: flex;
}
.active {
  background: lightblue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="example">
  <h3>{{ selectedOption }}%</h3>
  <option-group :list="selectedOption" @item-selected="itemSelected" />
</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

Issue with Material-ui IconButton's edge properties not functioning as expected

Is there a way to position the delete icon on the right side of the screen? It seems like using edge= "end" is not working as expected. If you'd like to take a look, here is the sandbox link: https://codesandbox.io/s/admiring-silence-vwfoe? ...

Bidirectional data binding in AngularJS for <option> elements generated from an AJAX request

I have built a Controller called WebsiteController with the following functionality: JApp.controller('WebsiteController', function($scope, $resource) { var UsersService = $resource('/auth/users', {}); $scope.adding = false; ...

My preference is for the most straightforward ajax form application available

I'm looking to create an ajax application that can handle a basic form with just text input and a submit button. I don't need any validation included, just a simple PHP script to process the form data. I'm reaching out for help because I hav ...

Using jQuery to show text upon hover using a `for` loop

I'm currently working on a webpage and incorporating a feature where hovering over specific div elements triggers the display of certain text in another div. There are 5 elements that I want to make hoverable and show text upon interaction. After imp ...

Trouble with ScrollView not scrolling on Nativescript-Vue

I am facing an issue with a scrollable view in my project. I have a list of items that should be scrollable, but for some reason it is not scrolling as expected. The structure involves a vertical stack layout wrapped in a scrollview, and inside the stackla ...

I'm puzzled as to why this code snippet consistently produces a range of 50 to 100 repeated values. This piece of code is crucial for altering the behavior of a function based on a specific

Below is a snippet of my React code aiming to alter the functionality of a function based on a specific window width: const [windowWidth, setWindowWidth] = useState({ winWidth: 0 }); useEffect(() => { window.addEventListener('resize', ( ...

Leveraging JSON for parsing xmlhttp.responseText to auto-fill input fields

Is there a way to utilize JSON for parsing xmlhttp.responseText in order to populate textboxes? I've been struggling to achieve this using .value and .innerHTML with the dot notation, along with b.first and b.second from the json_encode function in th ...

Utilizing Vue JS to set an active state in conjunction with a for loop

Currently in Vue, I have a collection of strings that I am displaying using the v-for directive within a "list-group" component from Bootstrap. My goal is to apply an "active" state when an item is clicked, but I am struggling to identify a specific item w ...

Data Binding in AngularJS appears to be non-functional

Experimenting with AngularJS, I created a small code snippet that doesn't seem to bind data properly. Here is the HTML and JS code for those who prefer not to visit the provided link: first.html <!doctype html> <html ng-app="firstApp"> & ...

Interacting with PHP through JavaScript function calls

I am facing some frustration with my website due to an issue involving PHP. When I retrieve data from a PHP file, it returns a JSON list like this: {"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurst ...

Creating users or custom roles in MongoDB on a NodeJS server is not currently possible

I have been attempting to directly create users on my database through our Express server, utilizing MongoDB 3.4 for the backend. Below is the current code snippet from the server: const express = require('express'); const bodyParser = require(& ...

Is it possible for jQuery UI Tabs to load entire new HTML pages?

In my index.html file, I have set up 3 different tabs. Using the jQuery UI function tabs(), I am attempting to load an HTML page via Ajax. Each HTML page includes the jQuery library and contains the following code: <link type="text/css" href="css/redmo ...

Incorporating real-time meta tags retrieved from an API into a static Nuxt.js website

I am working with a static site using Nuxt and fetching content from Strapi. I am trying to dynamically set the meta tags by fetching them asynchronously. On my site, there is an index page that passes the fetched data to either index-web or index-mobile ...

When attempting to run `npm install`, an error message is received indicating a network connectivity issue: "npm ERR

When I try to run npm install, I encounter an error. Here is the error message: 71 error code ETIMEDOUT 72 error errno ETIMEDOUT 73 error network request to https://registry.npmjs.org/@angular%2fanimations failed, reason: connect ETIMEDOUT 151.101.112.16 ...

How can Angular JS detect the names of the CSS files being used in an HTML page?

I am in the process of developing a brand new widget where we are incorporating a unique feature that displays the number of CSS files included within an HTML page. Our team requires the count and names of all CSS files utilized on the webpage. While I a ...

Ensure that a Vue component is able to verify whether a Vuex store state property contains any existing data

My current setup involves fetching the state "categories" asynchronously from a JSON endpoint. However, whenever I reload the page, the categories always appear empty when I try to work with this data in the component. methods: { onSubmit() { ...

Iterate through the form fields and save the information into an object

I am attempting to create a JavaScript object by looping through form inputs. const data = {}; // loop through each input found in form $('#form_name').filter(':input').each(function() { const $id = $(this).attr('id'); c ...

Tips on adding several elements to an array depending on the selected value from various checkboxes?

I am working on a project where I need to populate an array based on selected checkboxes. Let's assume we have 3 arrays containing strings: const fruits = ["Apple", "Banana", "Orange", "Grapes"]; const vegetable ...

Error caused by MongoClient TypeError

As a newcomer to NodeJS and someone exploring Dependency Injection for the first time, I encountered an error that led me to seek help. Before asking my question, I reviewed some similar threads on Stack Overflow: [1][2] Upon running my main code, I recei ...

Ensuring the Accuracy of POST Parameters Using Express-Validator

I've been working on adding parameter validation to my Node/Express API by utilizing express-validator. However, I encountered a situation where even though I sent a POST request with a missing "name" field using the curl command curl -X POST -d "foo= ...