1

I'm trying to call a child component's method from my parent component using $refs. It works if I do it the regular way: this.$refs.actualNameOfTheChildComponent.someMethod()

But for my app's needs I have to use a variable name instead of the child component's actual name:

const previousAction = `action${i-1}`
this.$refs.previousAction.showConflict()

In the second line, Vue doesn't understand that I'm not referring to a child component named previousAction, but I'm referring to a child component whose name is the value of the variable previousAction.

What's the right way to do it?

1 Answer 1

1

Writing .something is just syntactic sugar for ["something"]. Therefore you can use:

const previousAction = `action${i-1}`
this.$refs[previousAction].showConflict()

You can read more about the differences between dot notation and bracket notation here.

There are some important differences between dot and bracket notation:

Dot notation:

  • Property identifies can only be alphanumeric (and _ and $)
  • Property identifiers cannot start with a number.
  • Property identifiers cannot contain variables.
  • OK — obj.prop_1, obj.prop$
  • Not OK — obj.1prop, obj.prop name

Bracket notation:

  • Property identifiers have to be a String or a variable that references a String.
  • It is okay to use variables, spaces, and Strings that start with numbers
  • OK — obj["1prop"], obj["prop name"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.