Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What’s the best approach to compute distance between DOM Elements in Vuejs?

I'm building a tool to generate pdf file from data, and I need to build in two formats : 105mm * 148mm and 105mm * 210mm. So I got my entire document and now it's time for me to insert page breaks. I do it with a simple class:

.page-break { display: block; page-break-before: always; }

Now I have to insert this class into my v-for loop. So a basic idea is to compute an interval, like each the index is a multiple of 6, I insert one. But it's not the best way to do it, I want to insert a break when the content is above 90mm.

In order to do that, I wanted to compute the distance between 2 breaks and insert a new one if the distance is near 90mm. But, I can't find a way to access to my dynamic DOM elements...

So the question is simple: How to compute this distance? Or if there is a better way to achieve my goal, what can I improve?

like image 711
Existe Deja Avatar asked Dec 06 '16 11:12

Existe Deja


1 Answers

I believe you are adding a div/component in each v-for and you can add an unique id to each div. Now below methods can give you height of one div in px, and you will have some way to convert px to mm.

If you are using jquery, you can do

$('#nthDiv').height();

If not, you can do following:

inner height:

document.getElementById('#nthDiv').clientHeight;

outer height:

document.getElementById('#nthDiv').offsetHeight; 

if you have following code:

<div v-for="(item, index) in items" :class="{'page-break': isBreakNeeded(index)}" :id="index + 'thDiv'">
   ///Your code
</div>

You need to add following method:

isBreakNeeded (index) {       
   var height = 0
   do {
      index -= 1;
      height += document.getElementById('#' + index + 'thDiv').offsetHeight; 
      } while (index >= 0 || pageBreakAdded[index] == true)
      if(height > threshold){
         pageBreakAdded[index] = true
         return  true
      }
      else{
         return  false
      }
}

You need to add a following hash as well in the data attribute of your vue element, which will keep track of at what indexes you have added page break:

pageBreakAdded: {}
like image 197
Saurabh Avatar answered Oct 04 '22 17:10

Saurabh