Vue $refs and kebab case

2019-03-27 12:05发布

In vue 1 it was possible to do this:

<app v-ref:test-app></app>

and then reference it like so:

vm.$refs.testApp;

however in vue 2 the syntax for the ref has changed to:

<app ref="test-app"></app>

but this no longer can be referenced by

vm.$refs.testApp

instead it only works if:

<app ref="testApp"></app> 

which in standard DOM stuff isn't allowed. Is it a bug? can kebab case no longer be used?

标签: vue.js vuejs2
1条回答
老娘就宠你
2楼-- · 2019-03-27 12:48

Since the syntax has been changed from that of a namespaced element attribute (i.e., v-ref:foo-bar) to a normal key-value-pair attribute (i.e., ref="fooBar"), the implicit kebab-case-to-camel-case conversion is no longer applicable because the reference name is a plain string and is not constrained by having to conform to the requisite lowercase-kebab-case HTML syntax.

In other words, you can identify a ref with any string, so it wouldn't make sense for Vue to manipulate it. Have a look at this CodePen for an example in action of what I mean.

But, basically, a plain string ref value means you can define a reference like this:

<div id="app" ref="test ** app!"></div>

and reference it from Vue like this:

this.$refs['test ** app!']

In short, no, it's not a bug but no, automatic kebab-case conversion no longer takes place.

查看更多
登录 后发表回答