【问题标题】:How to include an input to v-for in scoped slot?如何在作用域插槽中包含 v-for 的输入?
【发布时间】:2017-08-27 08:23:53
【问题描述】:

我今天刚刚在 Vue 官方教程上了解了 slot。在阅读时,我在作用域插槽上遇到了这个示例:https://vuejs.org/v2/guide/components.html#Scoped-Slots

我通过为每个项目添加一个输入字段进行了一些实验。

家长:

<my-list :items="items"> 
    <template slot="item" scope="props">
        <li class="my-fancy-item">{{ props.text }}</li>
    </template>
</my-list>

子模板:

  <ul>
     <slot name="item" v-for="item in items" :text="item.text">
     </slot>
     <div> // this will appear at the end of list
         <input v-model = "message"> 
     </div>
     <p>{{message}}</p>
  </ul>

我的第一次尝试是将输入移动到父作用域并调用子函数,方法是使用 props 将索引和输入值传递给子函数来修改原始数组。它按预期工作。

另一种尝试是在父作用域上进行绑定,但它不起作用,因为父作用域看不到子属性:https://vuejs.org/v2/guide/components.html#Compilation-Scope

插入此输入以使其出现在每个项目中并且仍然能够将输入绑定到子属性的最佳方法是什么?

【问题讨论】:

  • message 来自哪里?您真的想要一个可以编辑每个item.text 的输入吗?
  • @BertEvans message 来自孩子。我想将输入绑定到message。我只是好奇是否可以让每个可编辑的item.text 仍然使用作用域插槽。
  • 您想要一个输入来编辑每个列表项的消息,还是只需要底部的一个输入?
  • @BertEvans 一个输入,用于编辑每个列表项的消息。抱歉,原始代码让您感到困惑。我只是想表明我不确定该输入字段应该放在哪里,因为它只出现在底部。
  • 那么更像这样? codepen.io/Kradek/pen/RpveGy

标签: vuejs2


【解决方案1】:

根据我们的讨论,我认为基本上你想要的是这个。因为您希望message 可以独立编辑,所以它必须是项目的一部分。如果您将message 设为my-list 的一部分,那么所有消息都将相同。之后,您需要做的就是将item 传递给作用域模板。

Vue.component("my-list",{
  props:["items"],
  template: "#my-list-template",
})

new Vue({
  el:"#app",
  data:{
    items:[
      {text: "item 1", message: "message 1"},
      {text: "item 2", message: "message 2"},
      {text: "item 3", message: "message 3"}
    ]
  }
})

还有模板:

<div id="app">
  {{items}}
  <my-list :items="items"> 
      <template slot="item" scope="props">
        <li class="my-fancy-item">{{ props.item.text }}</li>
        <div> 
             <input v-model="props.item.message"> 
         </div>
         <p>{{props.item.message}}</p>
      </template>
  </my-list>

</div>

<template id="my-list-template">
  <ul>
     <slot name="item" 
           v-for="item in items" 
           :item="item">
    </slot>
  </ul>
</template>

这里是working example

【讨论】:

    猜你喜欢
    • 2020-12-26
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 2020-01-01
    • 2019-11-08
    相关资源
    最近更新 更多