vue.js - Vue 和 Bootstrap Vue - 动态使用插槽

标签 vue.js bootstrap-vue

我正在尝试在 bootstrap-vue 表中创建一个插槽,以使用自定义组件呈现任何 bool 值。

所以我有一个简单的表格

<b-table :items="items" :fields="columns" >

</b-table>

现在,如果我想以特定方式渲染单个列,我必须使用插槽

<template v-slot:cell(active)="data" >
    <my-component :item="data.item" />
</template>

它有效,因为我知道 active 是一个 bool 值。

我想概括这种行为,但我无法在模板中使用v-for,也无法使用v-slot:cell(active) 如果不在模板上...想法是创建一个包含所有 bool 字段的数组并对其进行迭代...但它不起作用..

类似这样的事情

<template v-slot:cell(b)="data" v-for="b in booleanFields">
    <my-component :item="data.item[b]" />
</template>

最佳答案

因为Vue支持Dynamic Slot Names ,您可以使用变量来设置插槽名称 v-bind:[attributeName]="value"语法。

这样你就可以做类似的事情:

<template v-slot:['cell(' + b + ')']="data" v-for="b in booleanFields">

但是由于 dynamic argument expression constraints 而无法使用引号。因此,您必须创建一个辅助方法来执行该连接。所以:

<template v-slot:[gomycell(b)]="data" v-for="b in booleanFields">

加上

methods: {
  gomycell(key) {
    return `cell(${key})`; // simple string interpolation
  }

当然,您可以将方法 gomycell 命名为 cell 并像 v-slot:[cell(b)]="data"< 一样使用它 (注意 []),但我留下了名称 gomycell,这样在这个 texample 中就可以更清楚什么是方法的名称,什么不是.

<小时/>

演示:

这是一个小演示,展示了 dynamic slot names用法,它不是 b-table 但我认为它足以表明它是可能的:

Vue.component('my-table', {
  template: '#my-table',
})

new Vue({
  el: '#app',
  data: {
    booleanFields: [true, false]
  },
  methods: {
    gomycell(key) {
      return `cell(${key})`;
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <my-table>
    <template v-slot:[gomycell(b)]="data" v-for="b in booleanFields">
      <h3>who? {{ data.is }}</h3>
    </template>
  </my-table>
</div>

<template id="my-table">
  <div>
    <div style="color:green"><slot name="cell(true)" v-bind="{is: 'true!'}"></slot></div>
    <div style="color:red"><slot name="cell(false)" v-bind="{is: 'false!'}"></slot></div>
  </div>
</template>

关于vue.js - Vue 和 Bootstrap Vue - 动态使用插槽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58140842/

相关文章:

javascript - 如何将复选框设置为 Bootstrap Vue 表的第一个字段

twitter-bootstrap - 使 bootstrap-vue b-table 'Id' 列不可见

javascript - 我可以在没有 require 的情况下使用 Vue 吗?

vue.js - 验证 : How to add an avatar or an icon to the bottom of a navigation drawer

javascript - 如何在 v-for 上分配 v-model(来自 bootstrap vue 示例)

javascript - 如何在 Vue.js 中的方法内触发输入焦点事件?

javascript - BootstrapVue 访问 slot 模板中的 b-table 行数据

javascript - Vue.js - 在单个文件组件中使用子组件

javascript - VueJS 忽略全局导入

javascript - 如何在多个 Axios 调用上运行回退?