Home > OS >  How to reuse vue method for different form inputs
How to reuse vue method for different form inputs

Time:08-02

I am making a gaming character creator menu, which has a lot of form inputs that essentialy work the same way, incrementing an attribute up or down by one on button click.

I am fairly new to using Vue and would like to be able to pass the character attribute eg. 'torso' aswell from the form element to my increase() and decrease() methods without to repeat code. Currently I can change by hardcoding in the this.form.heads or this.form.heads-- but would like to do something like this.form.val with val being which ever form element was clicked.

index.html

<form>
    <div >
        <div >
            <div >
                <label >Head Type</label>
            </div>
            <div >
                <div  @click="decrease()"></div>
                <label >Type {{form.heads}}</label>
                <div  @click="increase()"></div>
            </div>
        </div>
        <div >
            <div >
                <label >Torso Type</label>
            </div>
            <div >
                <div  @click="decrease()"></div>
                <label >Type {{form.torso}}</label>
                <div  @click="increase()"></div>
            </div>
        </div>
    </div>
</form>

app.js (cut down a little to focus on the issue)

const APP = new Vue({
  el: '#app',
  data: {
    step:1,
    display: false,
    form: {
      albedo:'mp_head_mr1_sc08_c0_000_ab',
      heads:1,
      torse:1,
    },
  },
  methods: {
    OpenUI() {
      this.display = true
    },
    CloseUI() {
      this.display = false
      $.post('https://parks_creator/CloseUI')
    },
    decrease(){
      this.form.heads--;
      $.post('https://parks_creator/inputchange', JSON.stringify({
          data: this.form        
      }))
    },
    increase(){
      this.form.heads  ;
      $.post('https://parks_creator/inputchange', JSON.stringify({
          data: this.form        
      }))
    },
    prev() {
      this.step--;
    },
    next() {
      this.step  ;
    },
    change(){
      $.post('https://parks_creator/inputchange', JSON.stringify({
          data: this.form        
      }))
    },
  },
  computed: {},
  watch: {

  },
  
})```

CodePudding user response:

You can pass a character attribute to your methods as a parameter.

script:

methods: {
  decrease(attribute){
    this.form[attribute]--
  },

  increase(attribute){
    this.form[attribute]  
  }
}

template

<div @click="increase('heads')" />
<div @click="decrease('heads')" />

<div @click="increase('torso')" />
<div @click="decrease('torso')" />
  • Related