1
\$\begingroup\$

I have following code but wonder if I can loop it instead of copy-pasting.

calculator.ts

data: function() {
  return {
    calcInput: 'user types some value in input with v-model'
  }
},
template: `
  <span
    class="calc-button-control"
    @click="evaluate()"
    @keyup.enter="evaluate()"
  >calc</span>

  <span
    class="calc-button-control"
    @click="calcInput = calcInput.substring(0, calcInput.length - 1) "
    @keyup.del="calcInput = calcInput.substring(0, calcInput.length - 1) "
  >del</span>

  <span
    class="calc-button-control"
    @click="calcInput = ''"
    @keyup.esc="calcInput = ''"
  >clr</span>
`

Pass modifier to v-on:keyup is the hardest part here.
@[loopedItem.key]={loopedItem.method} - doesn't work.
In this case I can see in event listeners for example keyup.enter but it doesn't work.

\$\endgroup\$
1
  • \$\begingroup\$ Please state (maybe upfront) whether the code works, and just the coding alternatives listed close to the bottom didn't. \$\endgroup\$ Commented May 13, 2020 at 10:11

1 Answer 1

1
\$\begingroup\$

No.

Or well, maybe you could but I absolutely do not see any reason to do so.

What each <span> has in common:

  • The same class
  • They all have a click event and a keyup event

What each <span> has different:

  • They all have different handlers for what to do on the click/keyup event
  • They all have listen for different keyup events.

I don't see any benefit in creating a loop from this.

Some things you might want to consider though is:

  • Have a method that is performed for both click and the keyup event, to not copy-paste code between the different handlers.
  • Create a component for <span class="calc-button-control">

If you have plenty of more of these <span> elements, creating a component would be the way to go. Then you could have a component to handle the following:

  • It is a <span> element and applies the calc-button-control class.
  • It has a method for what to do when clicked or keyup event triggers.

I am not sure how flexible you can make the keyup listener, I don't think you can for example pass :keypress="enter" or similar to have it listen to @keyup.enter so I am not sure if creating a component for all of this does more harm than good.

\$\endgroup\$
1
  • \$\begingroup\$ Okay, thanks. Image the application, where you type a text from the screen (blind keyboard writing) and there will be a keyboard with all letters like on keyboard. When user types a letter, js have to listen for key press and set some animation class to that key. So I have to hard code it? \$\endgroup\$ Commented May 13, 2020 at 11:15

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.