0

I can't really explain this in words, but I want to bind my screen height to a calculated value. The code here does not work, so I'd like to know how to make it work.

<template>
    <b-container id="notfound-container">
        <b-row align-v="center" v-bind:style="{ height : h + 'px' }">
            <b-col style="align-items:center">
                <h1>404 Error</h1>
                <p>The page you have requested does not exist.</p>
            </b-col>
        </b-row>
    </b-container>
</template>

<script>
    export default {
        name: 'tHome',
        data () {
            return {
                h: (window.innerHeight - document.getElementById('notfound-container').getBoundingClientRect().top)
            }
        }
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
    h1, h2 {
        font-weight: normal;
    }
    ul {
        list-style-type: none;
        padding: 0;
    }
    li {
        display: inline-block;
        margin: 0 10px;
    }
    a {
        color: #42b983;
    }
</style>

The value does not need to be dynamically updated, but I'd like it to be calculated at least once. Currently, I get the error that "h" is not initialized.

1
  • It seems strange to get that error, as it works here jsfiddle.net/943bx5px/8 maybe check if you have a div notfound-container div or something Commented Dec 7, 2017 at 11:17

1 Answer 1

4

data properties are evaluated before the DOM is rendered. So perform your calculation logic after the DOM is mounted , i.e inside the mounted() lifecycle hook

data(){
    h: null
},
mounted(){
       this.h = (window.innerHeight - document.getElementById('notfound-container').getBoundingClientRect().top);
}

EDIT:

You can add an event listener for wimdow resize in the mounted() hook itself:

data(){
    h: null
},
mounted(){
    window.addEventListener('resize', this.setHeight);
},
beforeDestroy(){
    //remove the resize listener
    window.removeEventListener('resize', this.setHeight);
},
methods:{
    setHeight(){
        this.h = (window.innerHeight - document.getElementById('notfound-container').getBoundingClientRect().top);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

+1 I didn't know this actually. Is this described in the doc or did you get that from the vue lifecycles chart?
@samayo it is explained in the API section for lifecycle hooks: vuejs.org/v2/api/#Options-Lifecycle-Hooks
This is very good to know. How can I make it update whenever window.innerHeight changes? Or, even better, every tick?
@VamsiKrishna that was exactly what I was looking for. Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.