2

I'm calculating the container width and height using computed property and assigns it to the canvas in vue js.


export default {
...
  computed: {
    dimensions() {
      return document.getElementById(
        'canvas-container'
      );
    },
  },
...
}
<div id="canvas-container">
  <canvas
    v-bind:id="id"
    :height="dimensions.clientHeight"
    :width="dimensions.clientWidth"
  ></canvas>
</div>

But the issue is that I'm getting an undefined error like: cannot read the property clientHeight of null.

How can I avoid this.?

1
  • Is the component with the computed value the component containing canvas-container? Commented Sep 29, 2020 at 23:55

1 Answer 1

2

The canvas-container element doesn't exist yet when the dimensions computed property accesses it. The first render pass generates the virtual DOM but no actual DOM nodes are created yet.

You need to defer accessing the element until the component has mounted and the DOM element will exist.

There's no use using a computed property here since the DOM element is not reactive (it won't automatically update when the element resizes).

If possible, use a ref instead of using getElementById.

new Vue({
  el: '#app',
  
  data: {
    width: 0,
    height: 0,
  },
  
  mounted() {
    // Element is now available
    const el = this.$refs.el
    this.width = el.clientWidth
    this.height = el.clientHeight
  }
})
#app {
  border: 1px solid black;
  width: 200px;
  height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app" ref="el">
  Element size: {{ width }} x {{ height }}
</div>

If you need the dimensions to automatically update, you'll have to use some other mechanism for observing size changes such as a window resize listener or ResizeObserver.

Sign up to request clarification or add additional context in comments.

Comments

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.