1

I am writing a step through form and need to access the ref for each step in my Axios catch block in a DRY way.

Below, where it says stepOneObserver, I need stepTwoObserver, stepThree, stepFour, etc.

this.$refs.stepOneObserver.setErrors(error.response.data.errors);

Is it possible to use a variable for this?

if (observerStep === 1) {
    var obsStep = 'stepOneObserver';
}
this.$refs.{obsStep}.setErrors(error.response.data.errors);

I'm pseudo-coding, but basically want the {obsStep} to act as if it said stepOneObserver and reference that in the code.

Hope this is clear enough / makes sense.

Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
fylzero
  • 460
  • 6
  • 18

1 Answers1

3

You should access it using [] like :

 this.$refs[obsStep].setErrors(error.response.data.errors);

for more details check Property accessors

Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
  • Use this solution, plus a switch statement to set `obsStep`, that should make for clean code. – jacob13smith Sep 06 '19 at 21:15
  • 1
    Please try to search for duplicates instead of answering. This is an often-asked question: https://stackoverflow.com/q/4244896 – Andrew Li Sep 06 '19 at 21:15