首页 > 解决方案 > 在 Vue.js 的 v-for 循环中访问字符串数组值

问题描述

我需要从函数中的数组中获取字符串值。我在模板中声明的组件如下:

<video-preview v-for="video in playlist" vid-id="how-do-I-get-the-string
  -value-from-the-playlist-for-this-iteration"></video-preview>

这是在我的 .vue 文件playlist中声明的位置:data() { return {} }

playlist: [
  'videoID1',
  'videoID2',
],

这是我在methods同一个 .vue 文件部分中的函数:

playImageModal(video) {
  Analytics('content_viewed', vidId)
  // other functionality to play the video
}

我需要将playlist数组的当前值传递给 in 中的Analytics()函数playImageModal(),但是,我不太确定如何访问该值。我查看了 Vue.js 文档,当我的数组包含通用对象而不是字符串时,这很容易做到……我只是在模板中设置我的值时playlist会这样做。但是当有字符串数组时如何访问这些值?video.nameOfObjectAttributevid-id

标签: javascripthtmlvue.js

解决方案


I think you're just missing the :

<video-preview v-for="video in playlist" :vid-id="video"></video-preview>

it's also a good idea to include a key

<video-preview v-for="video in playlist" :vid-id="video" :key="video"></video-preview>

if you want to run a function you could (not should)

<video-preview v-for="(video, i) in playlist" :vid-id="playImageModal(video)" :key="i"></video-preview>

Usually you would run a function on some event catalyst (like @click=playImageModal(video), but that depends on what playImageModal does


推荐阅读