SamiulHSohan
SamiulHSohan

Reputation: 167

How to integrate this CodePen code into Vue?

I'm trying to implement this (https://codepen.io/iprodev/pen/azpWBr) in Vue. How can I do that?

I have tried to make implement this like this

<template>
    <div>
        <canvas height="100" id="confetti" width="100"></canvas>
     </div>
</template>

<script>
    export default {
        created () {
            // JS code from codepen
        }
    }
</script>

Upvotes: 1

Views: 445

Answers (1)

Harshal Patil
Harshal Patil

Reputation: 20960

Certainly, it is doable. There are a few things you need to do. All the code in the Codepen snippet is wrapped inside DOMContentLoaded event handler since you need access to actual DOM tree. With Vue, you cannot use this event as Vue applications are SPA and the loaded event will be fired much before your actual view is getting rendered.

In this case, you should use mounted event instead of created lifecycle event of the component. mounted ensures that component's DOM is actually attached to the main document.

Further, you will need access to the actual HTMLCanvasElement. Instead of locating it by ID, your Vue.js $refs construct like this:

<canvas ref="confetti" height="100" width="100"></canvas>

Inside your component, you can then access the DOM element as:

mounted() {
    this.$refs.confetti // Reference to HTMLCanvasElement
}

This is how you avoid using global id attributes with Vue.js. Now rest of the code is just how you want to organize it inside your component. You can abstract canvas rendering logic into a separate module and pass Canvas element or the methods can become part of Vue instance.

Third and final. There are a couple of event handlers assigned on window object like resize. You have to ensure that you are cleaning them up when the component is getting destroyed. If you don't do this, then even if the component is destroyed, these events will continue to trigger handlers. For this use beforeDestroy lifecycle event provided by Vue. Clean up all your globally registered event handlers.

Upvotes: 3

Related Questions