Is there an easy way to determine if an element inside a Vue component is overflowing?

I created a unique component called ResultPill which includes a tooltip feature (implemented using vuikit). The text displayed in the tooltip is determined by a getter function called tooltip, utilizing vue-property-decorator. Here are the relevant parts of the code:

<template>
    <div class="pill"
         v-vk-tooltip="{ title: tooltip, duration: 0, cls: 'some-custom-class uk-active' }"
         ref="container"
    >
        ..content here..
    </div>
</template>
<script lang="ts"&g  t;
    @Component({ props: ... })
    export default class ResultPill extends Vue {
    ...
        get tooltip (): string { ..calculating tooltip.. }
        isContainerSqueezed (): boolean {
            const container = this.$refs.container as HTMLElement | undefined;
            if(!container) return false;
            return container.scrollWidth != container.clientWidth;
        }
    ...
</script>
<style lang="stylus" scoped>
    .pill
        white-space pre
        overflow hidden
        text-overflow ellipsis
    ...
</style>

I am currently working on adding additional content to the tooltip when the component's width exceeds that of its container, triggering overflow styles. I tried checking this with $0.scrollWidth == $0.clientWidth in the console (where $0 represents the selected element), but encountered issues with this.$refs.container being undefined for many component instances. Do I need to assign unique references per component instance? Are there any other problems with my current approach? How can I determine if the element is overflowing?

In an attempt to address the potential issue of non-unique refs, I added a random id property to the class:

        containerId = 'ref' + Math.random();

and used it like so:

         :ref="containerId"
    >
    ....
            const container = this.$refs[this.containerId] as HTMLElement | undefined;

However, this did not resolve the tooltip alteration problem.

Additionally, I explored using the $el property instead of refs, but encountered similar challenges. It appears that the root cause may be related to this:

An important note about the ref registration timing: because the refs themselves are created as a result of the render function, you cannot access them on the initial render - they don’t exist yet! $refs is also non-reactive, therefore you should not attempt to use it in templates for data-binding.

(presumably the same is applicable to $el) Therefore, I must find a way to recalculate the tooltip upon mounting. I came across this question, but the provided solution does not suit my scenario.

Answer №1

As previously mentioned in one of the revisions, it is advised in the documentation not to utilize $refs for the initial rendering phase due to their undefined state at that time. Therefore, I have modified tooltip to be a property rather than a getter and perform its calculation within the mounted lifecycle hook:

export default class ResultPill extends Vue {
...
    tooltip = '';
    calcTooltip () {
        // The specific logic here is irrelevant; what matters is that this.isContainerSqueezed()
        // works accurately at this stage
        this.tooltip = !this.isContainerSqueezed() ? this.mainTooltip :
            this.label + (this.mainTooltip ? '\n\n' + this.mainTooltip : '');
    }
    get mainTooltip (): string { ..previously used calculation.. }
    ...
    mounted () {
        this.calcTooltip()
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Spacing applied to content within a fresh Vue application

Having been assigned the task of developing a Vue page for my team, I am facing an issue with a persistent white border surrounding the entire page. <script setup lang="ts"> </script> <template> <body> <div>&l ...

Tips for displaying and sorting two requests within one console

I am currently working on a project to display both folders and subfolders, but only the folders are visible at the moment. function getParserTypes (types, subject) { return types.map((type) => { return { id: type.entry.id, name: type. ...

VueJS waits until the loop is complete before executing a re-render

Check out this VueJS code snippet: new Vue({ el: '#app', data: { tiles: [ { isActive: false }, { isActive: false }, { isActive: false }, { isActive: false }, { isActive: false } ] }, methods: { ...

Ajax is updating the information stored in the Data variable

Recently, I reached out to tech support for help with an issue related to Ajax not executing properly due to Access-Control-Allow-Origin problems. Fortunately, the technician was able to resolve the issue by adding a file named .htaccess with the code Head ...

Updating NPM yields no changes

Having trouble updating dependencies in a subfolder of my MERN stack app. Specifically, I am trying to update the dependencies in the client folder where the React code is located. However, when I attempt to update the dependencies in the client folder, it ...

Getting JSON key and value using ajax is a simple process that involves sending a request

There is a JSON data structure: [{"name":"dhamar","address":"malang"}] I want to know how to extract the key and value pairs from this JSON using AJAX. I attempted the following code: <script type="text/javascript> $(document).ready(function(){ $ ...

How can you obtain values from a nested JSON object and combine them together?

I have a javascript object that is structured in the following format. My goal is to combine the Name and Status values for each block and then store them in an array. { "datatype": "local", "data": [ { "Name": "John", ...

Verifying the functionality of a custom directive in Angular 2 (Ionic 2) through unit

In my ionic application, I developed a custom directive specifically for text masking, aimed at formatting phone numbers within input fields. The core functionality of this directive revolves around utilizing ngControl to facilitate the retrieval and assig ...

Exploring React-Query's Search Feature

Looking for guidance on optimizing my Product search implementation using react-query. The current solution is functional but could be streamlined. Any suggestions on simplifying this with react-query would be greatly appreciated. import { useEffect, use ...

Unexpected behavior: Angular4/Javascript Date object alters when timezone is specified in Date constructor

In my Angular 4 application, I encountered an issue with a date retrieved from an API call. The date is in the format '1990-03-31T23:00:00-06:00' and when attempting to create a Date object and retrieve the month using getMonth(), it returns the ...

Having trouble setting the selected option in Jquery by value?

I have exhausted all options found on the internet. What could I be overlooking? The desired option is not getting selected. Here is the troublesome section of code. I have also included some other attempts that I have commented out. If it helps, this li ...

Troubleshooting Media Queries Problems in HTML and CSS

Check out the code snippet below: //Modifying text content (function() { var texts = $(".altered"); var textIndex = -1; function displayNextText() { ++textIndex; var t = texts.eq(textIndex) .fadeIn(2000) if (textIndex < te ...

Transform a 2-dimensional array into Leaflet.js markers

Hey there, I'm currently facing an issue with generating markers using leaflet js. I have an object that includes multiple entries for each year, and my goal is to create a layer group for each year that can be toggled on and off. However, I've e ...

AngularJS - Issue: [ng:areq] The 'fn' argument provided is not a function, instead it is a string

I encountered an issue: Error: [ng:areq] Argument 'fn' is not a function, received string Despite following the recommendations of others, I still have not been able to resolve the problem. Below is the code snippet in question: controller. ...

Node.js and MySQL: Troubles with closing connections - Dealing with asynchronous complexities

I am currently working on a Node program to populate my MySQL database with data from files stored on disk. While the method I'm using seems to be effective, I am facing challenges in ensuring that asynchronous functions complete before ending the con ...

Is there a way to make divs expand on top of existing content when hovering over them, in order to avoid needing to scroll through overflow content? I am currently working with

I am working with 9 boxes contained within divs, each box includes data that exceeds the size of the box itself (represented by Some Text repeated for demonstration purposes). I am seeking a solution where hovering over any box will cause it to enlarge and ...

Troubleshooting Problems with Retrieving Data Using jQuery and

Having trouble fetching information from a JSON file, as the data variable is empty. I have already downloaded the JSON file, so it's not an issue with the server connection. Can anyone point out where I might be going wrong? function handle_geolocat ...

I am trying to retrieve the class name of each iframe from within the iframe itself, as each iframe has a unique class name

My index HTML file contains multiple Iframes. I am trying to retrieve the class names of all iframes from inside an iframe. Each iframe has a different class name. If any of the iframes have a class name of 'xyz', I need to trigger a function. I ...

Using requestAnimationFrame to animate several independent objects

I'm currently working on animating two different objects: a square and a circle. Each object has its own button to initiate the animation, which involves moving the object from left to right. However, I've run into an issue where clicking on one ...

Update the content according to the size of the screen

I'm currently working on a project where I need to redirect pages based on screen sizes. I have separate index files for the mobile and web versions of the website. In the web version's index file, I've added the following script: <scri ...