Home > Enterprise >  Passing Value from Clicked Button as a Prop
Passing Value from Clicked Button as a Prop

Time:09-27

I am a bit confused about how to pass a value defined inside a button to a child component. Basically, the value of a clicked button displaying a percentage should be the prop value. This prop value should change based on which value I click. Should I use a v-model? If so, how? Here's what I have so far...

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){
        return this.percentage = value;
      }
    },
    props:['percentage']
  }
</script>

Calculator.vue

<ButtonGroup :percentage="percentage"/>

CodePudding user response:

Try like this:

Vue.component('button-group', {
  template: `
  <div class="">
    <ul>
      <li v-for="(percent, i) in percentages" :key="i">
        <button class="button" 
                @click="setPercent(percent)"
                :class="selPercent === percent && 'selected'">
          {{ percent }}%
        </button>
      </li>
    </ul>
  </div>
  `,
  props:['percentage'],
  data(){
    return{
      selPercent:  this.percentage,
      percentages: [5, 10, 15, 25, 50 ]
    }
  },
  methods:{
    setPercent(value){
      this.selPercent = value;
      this.$emit('percent-seted', value);
    }
  },
})

new Vue({
  el: '#demo',
  data() {
    return {
      percent: 5
    }
  },
  methods: {
    percentSeted(val) {
      this.percent = val
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
ul {
  list-style: none;
  display: flex;
}
.selected {
  background: violet;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <h3>{{ percent }}%</h3>
  <button-group :percetntage="percent" @percent-seted="percentSeted" />
</div>

  • Related