I have a table:
<b-table striped hover :items="coursesArray" :fields="fields"></b-table>
The data comes from
coursesArray: [
{
id: "1",
name: "foo",
teacherEmails: [{ 0: "sample1" }, { 1: "sample2" }, { 2: "sample3" }],
teacherIds: ["A1", "A2", "A3"],
},
],
And fields are:
fields: [
{ key: "id", label: "Course ID" },
{ key: "name", label: "Course Name" },
{
key: "teacherEmails",
label: "Teacher Email",
formatter: "teacherEmailTCellFormat",
},
{ key: "teacherIds", label: "Teacher ID" },
],
And this is how it's rendered without the formatter.
So, I added a custom formatter in fields to remove the brackets and curly braces.
The first problem I'm having is that looping over the value to return all the items in teacherEmails
does not work.
teacherEmailTCellFormat(value) {
console.log(value)
value.forEach(item => {
return each[0]
}
}
The second problem, that I don't understand why it's happening, is that if I log the value passed to the formatter, it's clear the formatter function is called twice.
Any help or clearance will be appreciated.
CodePudding user response:
You need to return an array, you can do this using Array#map
:
new Vue({
el:"#app",
data: () => ({
fields: [
{ key: "id", label: "Course ID" },
{ key: "name", label: "Course Name" },
{ key: "teacherEmails", label: "Teacher Email", formatter: "teacherEmailTCellFormat" },
{ key: "teacherIds", label: "Teacher ID" },
],
coursesArray: [
{
id: "1",
name: "foo",
teacherEmails: [{ 0: "sample1" }, { 1: "sample2" }, { 2: "sample3" }],
teacherIds: ["A1", "A2", "A3"],
}
]
}),
methods: {
teacherEmailTCellFormat(value) {
return value.map((item, i) => item[i]);
}
}
});
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css"/>
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<script src="https://unpkg.com/babel-polyfill@latest/dist/polyfill.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script>
<div id="app">
<b-table striped hover :items="coursesArray" :fields="fields"></b-table>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Note: I assumed the key represents the index of the item in the array, but you can change the mapping as you want. The main issue was returning the array.