【问题标题】:How to distribute components inside slots on child list如何在子列表的插槽内分配组件
【发布时间】:2016-10-15 10:00:25
【问题描述】:

我有一个接收项目列表的组件。这些项目中的每一个都将是主要项目中的一个子组件。每个子组件都有一个插槽,我需要在其中分发内容。

如何将每个项目的内容(名称)分配到正确的插槽?

根应用程序:

<div id="app">
  <test-list :items="items"></test-list>
</div>

var app = new Vue({
  el: "#app",
  data: {
    items: [
        {id: 1, name: "item 1"},
        {id: 2, name: "item 2"},
        {id: 3, name: "item 3"},
        {id: 4, name: "item 4"},
        {id: 5, name: "item 5"},
    ]
  }
});

主要组件:

Vue.component('test-list', {
  template: '#test-list',
  props: {
    items: []
  },
});

<script id='test-list' type='x-template'>
  <ul class="list-group">
    <test-item v-for="item in items" :id="item.id" :name="item.name"></test-item>
  </ul>
</script>

子组件:

Vue.component('test-item', {
  template: '#test-item',
  props: {
    id: 0,
    name: ""
  }
});

<script id='test-item' type='x-template'>
  <li class="list-group-item">
    <slot>default text {{name}}</slot>
  </li>
</script>

我能做的最好的事情就是在所有项目上分发相同的内容:JSFiddle here

有什么想法吗?谢谢!

【问题讨论】:

    标签: javascript vue.js vue-component


    【解决方案1】:

    如果我没看错,this 就是你想要的。你必须使用named slots,这样:

    根应用

    <test-list :items="items">    
    </test-list>
    

    主要组件

    <ul class="list-group">
        <test-item v-for="item in items" :id="item.id" :name="item.name">
            <span :slot="item.name"></span>
        </test-item>
      </ul>
    

    子组件

    <li class="list-group-item">
        <slot :name="name">default text {{name}}</slot>
      </li>
    

    注意事项:

    1. slot 组件包含在子组件中,具有 name 属性
    2. 槽中的元素被放置在具有slot 属性的父元素中。
    3. 两个属性都有一个v-on 指令(我使用了: 简写),所以你可以绑定你的Vue 实例的内容

    希望对你有帮助。

    【讨论】:

    • 感谢您的回答 Yerko,但您的示例不起作用。它应该显示 标记,而不是默认文本。我还需要从根应用分发内容,而不是从主组件的 v-for 分发。
    猜你喜欢
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 2017-05-22
    • 2019-07-30
    • 1970-01-01
    • 2021-01-14
    • 2014-05-20
    相关资源
    最近更新 更多