Vuetify v-treeview get node that was last clicked on - javascript

What is the easiest way to retrieve the (id of the) node that was just clicked on in a <v-treeview>? There is the update:open event that emits an array of all open nodes. I could temporarily store the whole array and compare a new version with the old one to see which element was added or removed. But this seems to be a bit cumbersome, right? I want to use the id of the node to dynamically reload the children of the children of the node from the backend, so that the user has the feeling that the data is already in the frontend. Maybe it is possible to emit in the update:open event not the whole array, but only the current node, somehow like this: #update:open="onExpand(item)"? (This throws the error Property or method "item" is not defined.)

You could use VTreeView's label slot, which passes the item itself in its slot props. In that slot, you could render a span with a click handler that also includes the item:
<template>
<v-treeview :items="items">
<template #label="{ item }">
<span #click="onItemClick(item)">{{item.name}}</span>
</template>
</v-treeview>
</template>
<script>
export default {
methods: {
onItemClick(item) {
console.log(item.id)
}
}
}
</script>

You can use update:active with the return-object prop. It will return the full object instead of the node id.
https://vuetifyjs.com/en/api/v-treeview/#props

Related

What is the Svelte way to reference the DOM element created by an {#each} block when it is clicked?

I'm reactively loading elements using Svelte's {#each} functionality, like so:
{#each $items as item}
<div>
<Button on:click={someFunction}>{item.text}</Button> (*)
</div>
{/each}
(*) a component which forwards its on:click
What I want to do is when someFunction is called by clicking the created item, reference the actual DOM element. I know you can reference the specific array item by passing the index to the function, but that gives me the array item, not a reference to the unique DOM element. How would one go about doing this?
Things I tried so far:
on:click={() => someFunction(this)}: returns undefined
on:click={(el) => someFunction(el)}: returns undefined
on:click={(e) => someFunction(e)}: followed by using e.target, which does return the button that is clicked, but would need .parentElement to get to the div, which doesn't seem like a very Svelte way.
on:click={someFunction}: combined with bind:this={anItem}, which of course only returns the last created element in the {#each} block.
If you just want the parent div, a quick and dirty solution would be to just use an Array.
A more elegant solution would be to wrap <Button> within a parent component and get the reference from there, through the context API for instance or a slotted prop.
<script>
let itemsElements = [];
const someFunction = (i) => console.log(itemsElements[i]); // <- this is your div
</script>
{#each $items as item, i}
<div bind:this={itemsElements[i]}>
<Button on:click={() => someFunction(i)}>{item.text}</Button>
</div>
{/each}
the button in question is a modal which I want to have an open/close functionality. So, upon clicking itself I want it to toggle the class "open". However, using the class directive this results in all buttons/modals generated by {#each} to simultaneously toggle the class.
That just means you are using the wrong property. If you have multiple objects you need to store the state per item and then use that for the class directive.
E.g.
{#each $items as item}
<div>
<Button on:click={someFunction}>{item.text}</Button>
<div class="modal" class:open={item.show}>...</div>
</div>
{/each}
Alternatively you can store the state in a separate list or a dictionary. You can also extract the content of the {#each} to a component which then can have a local state variable for the open state.

Check if an element contains a css class in React

There are multiple tabs like this:
<Menu.Item className="tab-title tab-multiple" key="key">
<p className="tab-title-text">
Tab title
<span className="items-counter">{showText}</span>
</p>
</Menu.Item>
the one that is the active/selected one, beside of its original class (tab-title tab-multiple) it also has active and its class looks like this: active tab-title tab-multiple
I want to show that element only if the class contains "active".
Is there a way to do this in React? Without taking in account onClick.
Tried with a ternary but it seems it does not work:
{element.classList.contains('active') ? (
<span className="items-counter">{showText}</span>
) : (<></>)}
Normally, you don't have to do that in React because you drive the classes on the element from state information in your component, and so you just look at that state information rather than looking at the class list. Your best bet by far is to do that, rather than accessing the DOM class list later.
If the active class is being added by something outside the React realm that's operating directly on the DOM element, you'll have to use a ref so you can access the DOM element.
To create the ref:
const ref = React.createRef();
To connect it to your React element, you add the ref property;
<Menu.Item className="tab-title tab-multiple" key="key" ref={ref}>
Then when you need to know, you check the current property on the ref:
if (ref.current && ref.current.classList.contains("active")) {
// ...
}
Beware that if you do that during a call to render (on a class component) or to your functional component's function, on the first call the ref will be null and on subsequent calls it'll always refer to the element for the previous version of the component. That element will probably get reused, but not necessarily.
React is driven by the data model (props & state). Use whatever data property you use to assign the active class name, to also hide/show the contents.
Another option is to use CSS:
.items-counter {
color: red;
}
.tab-title:not(.active) .items-counter {
display: none;
}
<div class="tab-title tab-multiple" key="key">
<p class="tab-title-text">
Tab title
<span class="items-counter">Not Active</span>
</p>
</div>
<div class="tab-title tab-multiple active" key="key">
<p class="tab-title-text">
Tab title
<span class="items-counter">Active</span>
</p>
</div>
You need to have an indicator, that maintains the active class.
let className ="";
if(isActive)
{
className = className +" active"; // props.isActive in case of child component
}
Now that you have added the className based on the flag.
instead of checking for,
if(element.classList.contains('active'))
you can check for,
if(isActive)
This is applicable for subcomponents also, where you read the isActive flag through props.

Get an array of DOM-Elements in vue js

I am trying to get an array of DOM-Elements in Vue.js. If I had the following HTML structure:
<select onchange="toggleDisability(this);" class="mySelect" id="mySelect1">
</select>
<select onchange="toggleDisability(this);" class="mySelect" id="mySelect2">
</select>
I could get all elements with the mySelect class with normal JS like:
var arraySelects = document.getElementsByClassName('mySelect');
Now I am trying to get the same thing with Vue $refs, but I am always getting the last element. it looks like:
<select id="selection-x" ref="Axis" #change="log($event)"></select>
<select id="selection-y" ref="Axis" #change="log($event)"></select>
and
log(selectElement){
var arraySelects = this.$refs['Axis'];
}
Of course there are also options ,so that #change event gets emitted, but it doesn't do what I want it to. I want to get an array of the elements with the same ref just like it works in the example above for normal JS, where you are getting an array of select elements whose class attribute equals to mySelect.
P.S. I know ref should be unique, but how could it be then used for this particular usecase?
No. It is not possible with ref and $refs. If you wish to do DOM manipulation then, use vue-directive or directly access DOM from the root element of the component like:
Vue.extend({
mounted() {
// Do what you want with your children.
const children = this.$el.querySelectorAll('.mySelect');
}
})
For me the best way to do this was to set a ref on the parent element (thanks joaner in original comment), but then I also needed to run my code in the "updated" hook so my data was loaded before trying to access the dom (I also have a v-if on the same element I want to reference children):
template:
<ul v-if="dataLoaded" ref="eventlist">
<li class="eventItem"></li>
<li class="eventItem"></li>
<li class="eventItem"></li>
</ul>
javascript:
updated() {
let eventItems = this.$refs.eventlist.children
console.log(eventItems)
}

Aurelia conditionally wrapping slots in components

I'm creating Aurelia components which wrap material-components-web, cards specifically right now and am wondering what's the correct way of implementing multiple content sections (actions, etc.).
Slots seem to be the right choice but I cannot just put the actions div on the template at all times, but only if any actions are actually present.
Simply put I need to check if a slot has been defined inside the component template.
<template>
<div class="card">
<div class="content">
<slot></slot>
</div>
<!-- somehow check here if the slot has been defined -->
<div class="actions">
<slot name="actions"></slot>
</div>
</div>
</template>
Out-of-the-box, there is no direct way to do this like a $slots property, however you should be able to access slots via the template controller instance itself: au.controller.view.slots - the specific slot inside of this array has more information about the slot itself and its children.
Here is an example of an Aurelia application with a modal component (custom modal element). The modal itself has a slot where HTML can be projected inside of it. We have a header, body and footer.
Each predefined slot inside of our custom element should show up inside of a children object, where the property name is the name of our slot. If you do not provide a name for a slot (the default slot) the name of it internally is: __au-default-slot-key__.
We first check if the slot exists and then we check the length of its children, the children array exists inside each slot. If a slot has no HTML projected into it, it will have a children length of zero. This is reliable, because default content defined inside of the slot does not get put into the children array, only projected HTML does.
You'll see the work is being done mostly inside of modal.html, but pay close attention to modal.js where we inject the element reference of the custom element and then access the Aurelia instance using au to get to the controller containing our slots itself.
There is one caveat with this approach: you cannot use if.bind to conditionally remove HTML inside of your custom element. If you use if.bind on a DIV containing a slot, it actually removes its slot reference so it can't be checked. To work around this, just use show.bind (as I do in my provided running example).
Use CSS :empty Selector
CSS is the right tool for this job, not Aurelia. The :empty selector will allow you to display: none the div.actions when the slot isn't populated.
.card .actions:empty {
display: none;
}
According to the :empty selector spec as explained by CSS-Tricks, white space will cause empty to fail to match, so we just need to remove the white space around the slot.
<div class="actions"><slot name="actions"></slot></div>
Working example here: https://gist.run/?id=040775f06aba5e955afd362ee60863aa
Here's a method I've put together to detect if any slots have children (excluding HTML comments)
TypeScript
import { autoinject } from 'aurelia-framework';
#autoinject
export class MyClass {
private constructor(readonly element: Element) {
}
private attached() {
}
get hasSlotChildren(): boolean {
if (!this.element ||
!(this.element as any).au) {
return false;
}
let childrenCount = 0;
const slots = (this.element as any).au.controller.view.slots;
for (let slotName of Object.keys(slots)) {
const slot = slots[slotName];
if (slot.children &&
slot.children.length > 0) {
for (let child of slot.children) {
if (child instanceof Comment) {
// Ignore HTML comments
continue;
}
childrenCount++;
}
}
}
return childrenCount > 0
}
}
HTML
<template
class="my-class"
show.bind="hasSlotChildren"
>
<slot></slot>
</template>

Radiobutton-like behaving Vue.js components

I have the following Vue.js components, which basically are supposed to have a radiobutton-like behaviour:
// Parent Component
<template>
<child-component
v-for="element in elements"
</child-component>
</template>
<script>
import ChildComponent from './Child.vue'
export default {
components: {
ChildComponent
},
props: {
elements: Array
},
methods: {
activate(e) {
for (let i of this.$children) {
i.active = false;
}
if (e < this.$children.length) {
this.$children[e].active = true;
}
}
}
}
</script>
and
// Child Component
<template>
{{active}}
</template>
<script>
export default {
props: {
active: Boolean
}
}
</script>
This works fine but only the parent can decide to activate one of the children (and thus deactivate all others).
I want however also be able to allow each child to activate itself (and by a magic property of its parent, deactivate all other siblings).
Obviously I do not want each child to know about its siblings and mess with their .active prop (super bad design).
I would rather not have a children communicate back up to the parent and call some method (still bad design as I could only reuse the child components in parents that have activate() method).
Instead I would like the parent to listen to changes to all children active props and take action when one of them changes. That way the parent entirely encapsulates the radio button behavior.
How can this interaction be implemented in Vue.js?
Take a look at two-way binding: http://vuejs.org/guide/components.html#Prop_Binding_Types
This allows you to sync a property's value in both directions, meaning the parent or the child has access to change the variable. Then you can watch for changes on the parent and update accordingly.
I think a better option would be to create a RadioSet component, which then would house a number of radio buttons. This would eliminate your concern about a parent having to have the activate() method. You could simply pass in an object with a series of id and values that could be used to generate the buttons.

Categories