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?
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"]