javascript - 如何在 v-for (vue.js) 中访问 <slot> 中的项目

标签 javascript vue.js

如何将项目从 v-for 发送到插槽?在 vue.js .

列表组件:

<ul>
  <li v-for="item in list">
    <slot></slot>
  </li>
</ul>

页面浏览量:

<list-component :list="list">
  <span v-text="item.value"></span>    
</list-component>

代码 <span v-text="item.value"></span>无法访问 item (来自组件的范围)。这是一种发送 item 的方式吗?从组件到标签中的代码?

P.S. 我知道,作为解决方法,我可以发送 $index从组件到父 View ,但有点 hacky


UPD:我当前解决方法的示例(有人可能会发现这很有用):

声明index在 View 的数据中:

data () {
  return {
    index: 0,
    list: [ ... ]
}

添加到 index View 模板的参数:

<list-component :list="list" :index="index">
  <span v-text="list[index].value"></span>    
</list-component>

声明index在组件的 Prop 中:

props: {
  index: {
    type: Number
  }
}

将索引添加到 v-for的元素:

<ul>
  <li v-for="item in list" index="$index">
    <slot></slot>
  </li>
</ul>

最佳答案

绑定(bind)表达式是在定义它们的上下文中编译的,所以:

v-text="item.value"

无法编译,因为在页面 View 中没有定义“项目”。

也许您可以尝试更改您的代码结构,如下所示:

列表组件:

//content in component
<span>i am text in component,item value is:{{item.value}}</span>
<slot></slot>

页面浏览量:

<ul>
  <li v-for="item in list">
      <list-component :item="item"></list-component>
  </li>
</ul>

关于javascript - 如何在 v-for (vue.js) 中访问 <slot> 中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37248411/

相关文章:

javascript - vuejs - 重复表行中的 <slot>

javascript - 使用 javascript 模数将类添加到每三个项目,但不希望将其应用于第一个 0

javascript - 是否可以隐藏父元素的父元素的子元素?

api - Vue 多个 api 包括

vue.js - VueJS 将计算数据作为 Prop 返回未定义

node.js - 如何在Windows上后台运行Vue应用程序

javascript - Google Analytics API - 获取仪表板的综合浏览量

javascript - 按名称单击事件在 jQuery 中不起作用

javascript - 允许子 iframe(跨站点)访问 window.top

ecmascript-6 - 将 vue 组件放入单独的文件中?