How to pass cell templates to a component with b-table? - vue.js

I created a component that shows table data for various pages. That component uses b-table inside. Now for a couple pages I want to customize rendering of some columns, and Bootstrap Tables allow that using scoped field slots with special syntax:
<template #cell(field)="data">
{{ data.item.value }}
</template>
where field - column name, coming from my array with columns, and data.item - cell item to be rendered.
The problem is that I have different fields for different pages, so this customization should come from parent component, and these templates should be created dynamically.
Here is how I tried to solve it:
Pass via property to MyTableComponent an array with customizable fields and unique slot names
In MyTableComponent dynamically create templates for customization, and inside dynamically create named slots
From parent pass slot data to named slots
MyTableComponent:
<b-table>
<template v-for="slot in myslots" v-bind="cellAttributes(slot)">
<slot :name="slot.name"></slot>
</template>
</b-table>
<script>
...
computed: {
cellAttributes(slot) {
return ['#cell(' + slot.field + ')="data"'];
}
}
...
</script>
Parent:
<MyTableComponent :myslots="myslots" :items="items" :fields="fields">
<template slot="customSlot1">
Hello1
</template>
<template slot="customSlot1">
Hello2
</template>
</MyTableComponent>
<script>
...
items: [...my items...],
fields: [...my columns...],
myslots: [
{ field: "field1", name: "customSlot1" },
{ field: "field2", name: "customSlot2" }
]
...
</script>
Unfortunately, b-table component just ignores my custom slots like if they are not provided. It works if I specify in the MyTableComponent it directly:
<b-table>
<template #cell(field1)="data">
{{ data.item.value }}
</template>
</b-table>
But I need it to be done dynamically via component properties. Please help.

You can use Dynamic Slot Names feature of Vue 2 to pass all (or some) slots from parent to <b-table> inside child like this:
Child:
<b-table>
<template v-for="(_, slotName) of $scopedSlots" v-slot:[slotName]="scope">
<slot :name="slotName" v-bind="scope"/>
</template>
</b-table>
$scopedSlots contains all slots passed to your component.
Now this will work:
<MyTableComponent :items="items" :fields="fields">
<template #cell(field1)="data">
{{ data.item.value }}
</template>
</ MyTableComponent>
UPDATE 2 - Vue 3
To make above code work in Vue 3, just replace $scopedSlots with $slots as suggested by migration guide
UPDATE 1
You can filter $scopedSlots if you want (have some slot specific to your wrapper component you don't want to pass down to <b-table>) by creating computed
I mentioned this possibility in my original answer but it is a bit problematic so it deserves better explanation...
Scoped slots are passed to a component as a functions (generating VNode's when called). Target component just executes those she knows about (by name) and ignores the rest. So lets say your wrapper has b-table (or v-data-table for Vuetify) inside and some other component, let's say pagination. You can use code above inside both of them, passing all slots to each. Unless there is some naming conflict (both components using same slot name), it will work just fine and does not induce any additional cost (all slot functions are already compiled/created when passed to your wrapper component). Target component will use (execute) only the slots it knows by name.
If there is possible naming conflict, it can be solved by using some naming convention like prefixing slot names intended just for b-table with something like table-- and doing filtering inside but be aware that $scopedSlots object does contain some Vue internal properties which must be copied along !! ($stable, $key and $hasNormal for Vue 2 - see the code). So the filtering code below even it's perfectly fine and doesn't throw any error will not work (b-table will not recognize and use the slots)
<b-table>
<template v-for="(_, slotName) of tableSlots" v-slot:[slotName]="scope">
<slot :name="slotName" v-bind="scope"/>
</template>
</b-table>
computed: {
tableSlots() {
const prefix = "table--";
const raw = this.$scopedSlots;
const filtered = Object.keys(raw)
.filter((key) => key.startsWith(prefix))
.reduce(
(obj, key) => ({
...obj,
[key.replace(prefix, "")]: raw[key],
}),
{}
);
return filtered;
},
},
This code can be fixed by including the properties mentioned above but this just too much dependency on Vue internal implementation for my taste and I do not recommend it. If it's possible, stick with the scenario 1...

Related

How to refer to specific dynamically added component from number of dynamically added components in Vue, version 2.9

What or where is individual id or any other element that I can call to run a function on component.
Example: using add button I'm dynamically creating colored squares. Each square has close button.
Then I want to delete one of squares, let's say the blue one (third child of template).
v-bind:id='var' doesn't works because then all squares have the same id.
You can use ref, you can define ref in every added component. The ref is array. you can refrence component through index of the ref.
for example;<div v-for="(item) in arr" :key="item.id"> <span ref="testRef"> item.name </span> </div>, you can use 'this.$refs.testRef[index]' find component which you want.
There are multiple options. For instance, in your v-for loop you can get the index this way: (official docs)
<div v-for="(item, index) in myList" :key="index">
{{ item.name }}
</div>
You could then for example use the index in a ref to access the element for the script.
Another option is to pass the event instance to the onclick listener with the special keyword $event, and use this to get the element:
<div ... #click="myFunction($event)">
{{ item.name }}
</div>
And then in your script
myFunction(ev) {
// do something with the element that was clicked on
console.log(ev.target)
}
However, a more 'vue' way would be to not mess with the elements, but only manipulate the underlying data and let vue worry about representing the data with elements on your page. For instance, you could make your squares be represented by a list of objects, containing their own data own the state (opened or closed). So in your script you have:
data() {
return {
squares: [
{ color: "ff0000", opened: true },
...
]
}
},
And in your template something like
<div
v-for="square in squares"
v-show="suare.opened"
#click="square.opened = false"
> ...

Vue - detect component inside slot

I have this slot inside my tile component. I basically need to detect a specific other component which is supposed to be used inside this slot BUT the slot also supports other html tags not just this specific component. Is there a way to detect a special component e.g. <listitem /> inside the slot?
<div class="tile">
<template v-if="$slots['headline']">
<slot name="headline" />
</template>
</div>
Edit
The basic idea is the following
<tile>
<template #headline>
<listitem />
</template>
</tile>
<tile>
<template #headline>
<h1>Some headline</h1>
</template>
</tile>
I have those two options on how you can utelise this header slot. If there is a just a normal html tag e.g. <h1>, I would like to apply the corresponding css styles. If there is the <listitem /> component I need to apply other styles
As content of the slot is passed to the component as an array of VNode's accessible via this.$slots (in case of scoped-slots it is function returning array of VNode's) you can write a function like this:
methods: {
isListitem() {
return this.$slots.headline && this.$slots.headline[0].tag.endsWith('-listitem')
}
}
Main problem is that $slots is not reactive
Docs:
Please note that slots are not reactive. If you need a component to re-render based on changes to data passed to a slot, we suggest considering a different strategy that relies on a reactive instance option, such as props or data
So I don't recommend doing this and follow the Vue documentation suggestion to use props instead...
Maybe you can use a function to try to get this element by js, something like this:
I am not sure if its will works
function checkElement(){
var listitem = document.querySelector("listitem");
if(listitem) {
// if exist do something
}
}

events and self referencing components vue.js

I have commenting system which allows 1 level thread. Meaning 1st level comment will look like
{
...content,
thread: []
}
where thread may have more comments in it. I though this is good for self-referencing component and List with Slots.
But after a while I do not know how to wire this thing up.
SingleComment component is given below
<template>
... *content*
<b-button
v-if="isCommentDeletable"
#click="handleDelete"
</b-button>
<div v-for="item in item.thread" :key="item._id">
<SingleComment class="ml-3"
:item="item"
/>
</div>
</template>
...
methods: {
handleDelete () {
this.$emit('remove')
},
}
...
components: {
'NewComment': NewComment, 'SingleComment': this
},
name: 'SingleComment'
}
</script>
List component classic list is recieving array of items as prop and is given by
<div v-for="item in items" ...
<slot
name="listitem"
:item="item"
/>
</div>
and this is the parent where I want to use these two components with modal
Parent
<AppModal
>
...
<List
class="my-1"
:items="comments.docs"
>
<template v-slot:listitem="{ item }">
<SingleComment
:item="item"
:remove="removeItem"
#remove="removeItem"
/>
</template>
</List>
I want to wire this thing up in Parent so I can use single modal for whole list.
Do I wire thins thing up with events? Or? Any sort of help is welcome. I am stuck. I can make some hacks but I really do not know how to deal with this self referencing components.
If you only have one level of nesting, you could simply pass the component itself as a slot, like so:
<Comment v-for="comment in comments" :key="comment.id" v-bind="comment">
<Comment v-for="thread in comment.thread" :key="thread.id" v-bind="thread" />
</Comment>
Then you will only have to worry about passing props one level deep, as if you only had a single list of comments. I created an example of this on CodeSandbox here: https://codesandbox.io/embed/vue-template-mq24e.
If you want to use a recursive approach, you'll just have to pass props and events around; there's no magic solution that steps around this. Update CodeSandbox example: https://codesandbox.io/embed/vue-template-doy66.
You could avoid explicitly passing the removeitem event listener down by having a removeitem action on your Vuex store that you map to your component.
My opinion here, is that simpler is better, and you don't need recursion for one level of nesting. Put yourself in the shoes of a future developer and make the code easy to read and reason about; that future developer may even be you when you haven't looked at the codebase in a few weeks.

Passing a property to a slot

I'm trying to find the "cleanest" way of passing a property to a child component.
I have a custom component (lets call it parent in this example) that can take any child component via a slot. Imagine the parent component wants to update some property x of a child.
The solution that I've come up with uses scoped slots, like so:
// parent.vue
<template>
… some template stuff
<slot :x="parentX"></slot>
</template>
<script>
...component setup
computed: {
parentX: function() {
return ...some number
}
},
...more component stuff
</script>
--
// child.vue
<template>
...some html that uses property x
</template>
<script>
...component setup
props: { x: Number },
...more component stuff
</script>
--
// app.vue
<template>
<parent>
<template scope="A">
<child :x="A.x" />
</template>
</parent>
</template>
This works, but it's not very nice for a couple of reasons:
The extra markup needed to wire then components together.
The fact that the user of these components needs to know about properties that they shouldn't need to know about. The parent component is sending an internal bit of state to it's child. The fact that I have to manually wire up this is a little annoying, especially because it's just boiler plate.
Is there a better way of doing this so I can say:
<template>
<parent>
<child />
</parent>
</template>
Then all I need to know is that the child has a property x.
UPDATE (28-10-18)
It's possible to remove some of the boiler-plate by using slot-scope directly on the child element. e.g.
<template>
<parent>
<child slot-scope="child" :x="child.x" />
</parent>
</template>
but the real problem still persists. I need to manually wire up the components in the app.vue even though this has already been fully defined in the parent and child components.
A slot is for uncoupled content. Your requirement is that the content be a component that takes a prop. It seems to me that what you want to do is pass the child component to the parent as a prop, and have the parent template do something like
<div :is="childComponent" :x="child.x"></div>

Providing the model for a component as a slot

Consider the following two custom elements in Aurelia (list & row):
row.html
<template>
<span>${name}</span>
</template>
row.js
export class Row
{
name = "Marry";
}
list.html
<template>
The List
<ol>
<li repeat.for="r of rows">
<slot name="rowItem" model.bind="r"></slot>
</li>
</ol>
</template>
list.js
import { bindable } from 'aurelia-framework';
export class List
{
#bindable
rows = [{name: "John"}];
}
The app will tie them together:
app.html
<template>
<require from="./list"></require>
<require from="./row"></require>
<list rows.bind="users">
<row slot="rowItem"></row>
</list>
</template>
app.js
export class App
{
users = [{name: "Joe"}, {name: "Jack"}, {name: "Jill"}];
}
The problem is that the model for the row is not set correctly. All I get as the output is the following:
The List
1.
2.
3.
So the question is; how can I provide the model for a slot in Aurelia?
Here's a Gist to demonstrate the problem in action.
Slots aren't going to work for what you want to do. It's a known limitation of slots in Aurelia. Slots can't be dynamically generated (such as inside a repeater).
Luckily, there's another option to accomplish what you want: template parts.
Template parts aren't well documented (my fault, I should have written the docs for them). But we have some docs in our cheat sheet. I've modified your gist to show how to use them: https://gist.run/?id=1c4c93f0d472729490e2934b06e14b50
Basically, you'll have a template element in your custom element's HTML that has the replaceable attribute on it along with a part="something" attribute (where something is replaced with the template part's name. Then, when you use the custom element, you'll have another template element that has the replace-part="something" attribute (again, where something is replaced with the template part's name). It looks like this:
list.html
<template>
The List
<ol>
<li repeat.for="row of rows">
<template replaceable part="row-template">
${row}
</template>
</li>
</ol>
</template>
app.html
<template>
<require from="./list"></require>
<require from="./row"></require>
<list rows.bind="users">
<template replace-part="row-template">
<row name.bind="row.name"></row>
</template>
</list>
</template>