I am using vuejs
with rails
webpacker and turbolinks
. I want to calculate the correct height of the iframe
element on the initial page load. Currently, I am getting the height of the element when I manually refresh the page, and when someone navigates from any other pages to the page where the iframe
element is located, the height of the element is not calculated.
My index.js
setup:
Vue.use(TurbolinksAdapter); document.addEventListener('turbolinks:load', () => { const app = new Vue({ el: '[data-behaviour="vue"]', }); });
My preview.vue
where the iframe
element is located.
data() { return { frameHeight: '', }; }, computed: { computeHeight() { this.frameHeight = this.$refs.iframe.contentWindow.document.body.scrollHeight + 'px'; }, }, mounted() { window.addEventListener('load', () => { this.computeHeight; }); },
I have tried replacing the mounted
hook with the created
hook as well, and instead of listening for the load
event I have tried listening for the turbolinks:load
event as well. But it doesn’t work.
Any help would be appreciated. Thanks.
Advertisement
Answer
Try wrapping the compute height code in nextTick like so:
data() { return { frameHeight: '', }; }, mounted() { this.$nextTick(() => { window.addEventListener('load', () => { this.frameHeight = this.$refs.iframe.contentWindow.document.body.scrollHeight + 'px'; }); }) },
This should allow the elements to load before executing the code to grab height.