简体   繁体   中英

Cannot bind `ref` when using `v-for`

I need to create polygons inside <svg>...</svg> so I used v-for like this:

<polygon v-for="id in polygonArr" :key="id" :ref="id" points="15,0 18.541,11.459 30,11.459 20.729,18.541 24.271,30 15,22.918 5.729,30 9.271,18.541 0,11.459 11.459,11.459" />

and in polygonArr is

data() {
  return {
    ...
    polygonArr: [1, 2, 5],
    ...
  }
},

But when I run it and check with the inspector tool, it shows like this

...
<polygon data-v-5567ea9e="" points="15,0 18.541,11.459 30,11.459 20.729,18.541 24.271,30 15,22.918 5.729,30 9.271,18.541 0,11.459 11.459,11.459"></polygon>
<polygon data-v-5567ea9e="" points="15,0 18.541,11.459 30,11.459 20.729,18.541 24.271,30 15,22.918 5.729,30 9.271,18.541 0,11.459 11.459,11.459"></polygon>
<polygon data-v-5567ea9e="" points="15,0 18.541,11.459 30,11.459 20.729,18.541 24.271,30 15,22.918 5.729,30 9.271,18.541 0,11.459 11.459,11.459"></polygon>
...

as you can see, :ref="..." isn't present in the output.

I tried changing :ref="i" to :refx="i" and it works perfectly as:

<polygon data-v-5567ea9e="" refx="1" points="15,0 18.541,11.459 30,11.459 20.729,18.541 24.271,30 15,22.918 5.729,30 9.271,18.541 0,11.459 11.459,11.459"></polygon>
<polygon data-v-5567ea9e="" refx="2" points="15,0 18.541,11.459 30,11.459 20.729,18.541 24.271,30 15,22.918 5.729,30 9.271,18.541 0,11.459 11.459,11.459"></polygon>
<polygon data-v-5567ea9e="" refx="5" points="15,0 18.541,11.459 30,11.459 20.729,18.541 24.271,30 15,22.918 5.729,30 9.271,18.541 0,11.459 11.459,11.459"></polygon>

Why is it like this? And how should I do to solve this? Other attributes such as title , etc. seem to work fine.

Because ref is used internally by Vue components to reference its children. In the Vue component that is rendering your <polygon> 's, you can access that ref via this.$refs . However, it won't show up in the HTML.

Not sure right now, but you may be able to inspect the ref attribute in the vue developer tools however.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM