Incorporating JavaScript initialization and execution of functions within a Vue component

Attempting to replicate @szimek's signature pad...

I constantly struggle with integrating pure JavaScript functions and initialization (like the one shown in the code below) into a Vue component.

New to Web Development, I realize my question may be trivial, but I appreciate your patience :)

var signaturePad = new SignaturePad(document.getElementById('signature-pad'), {
  backgroundColor: 'rgba(255, 255, 255, 0)',
  penColor: 'rgb(0, 0, 0)'
});
var saveButton = document.getElementById('save');
var cancelButton = document.getElementById('clear');

saveButton.addEventListener('click', function(event) {
  var data = signaturePad.toDataURL('image/png');

  // Send data to server instead...
  window.open(data);
});

cancelButton.addEventListener('click', function(event) {
  signaturePad.clear();
});
.wrapper {
  position: relative;
  width: 400px;
  height: 200px;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
img {
  position: absolute;
  left: 0;
  top: 0;
}

.signature-pad {
  position: absolute;
  left: 0;
  top: 0;
  width:400px;
  height:200px;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f98a909e97988d8c8b9ca689989db9cbd7cad7cb">[email protected]</a>/dist/signature_pad.min.js"></script>
<h1>
  Draw over image
</h1>
<div class="wrapper">
  <img src="https://preview.ibb.co/jnW4Qz/Grumpy_Cat_920x584.jpg" width=400 height=200 />
  <canvas id="signature-pad" class="signature-pad" width=400 height=200></canvas>
</div>
<div>
  <button id="save">Save</button>
  <button id="clear">Clear</button>
</div>

Answer №1

It is recommended not to include <script> tags in Vue component templates. Instead, import packages like so:

import SignaturePad from 'signature_pad'
.

The initialization code should be placed in the created or mounted hook.

In Vue, direct DOM manipulation should be avoided if possible. If necessary, refs should be used. Event handlers can be set directly in the template:

<div class="wrapper">
  <canvas ref="padRef" class="signature-pad" width=400 height=200></canvas>
</div>
<div>
  <button @click="save">Save</button>
  <button @click="clear">Clear</button>
</div>

Unlike traditional JavaScript, Vue components are meant to be destroyed at some point. Proper cleanup must be performed. For example:

mounted() {
  this.signaturePad = new SignaturePad(this.$refs.refPad, ...);
}
destroyed() {
  // perform cleanup
  this.signaturePad.off();
},
methods: {
  save() {
    var data = this.signaturePad.toDataURL('image/png');
    ...
  },
  clear() {
    this.signaturePad.clear();
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What sets apart the concept of asynchrony in C# from that in JavaScript?

When working with Python and JavaScript, a common issue arises due to blocking the event loop. This occurs when code is executed in a single thread and only one synchronous operation can be performed at a time. Interestingly, this problem does not seem t ...

Challenges arise when attempting to use AJAX to post data from a poll generated by PHP

Let me walk you through this step by step. I'm working on creating a dynamic poll that can be easily modified, requiring the use of Ajax to submit the form without page reload. To achieve this, I've created a PHP script to generate the poll and n ...

Angular7 & Electron: Resolving the Issue of Loading Local Resources

I am encountering difficulties while working with electron. Although I can successfully load my project using ng serve, I encounter an error when attempting to open it with electron as shown in the developer tools Not allowed to load local resource: fil ...

What are the steps to implement email validation, Saudi mobile number validation, and national ID validation in cshtml?

Looking to implement validations for the following fields: email, mobile number (must be 10 numbers and start with 05), and National ID (must be 10 numbers and start with 1 or 2) <input class="form-control" type="text" id="txt ...

Using Vue CLI to Display Components across Different Pages with Flask

I am currently working on a non-spa application that uses pages served by Python Flask. In an effort to transition to using vuecli for the benefits of ES6, I intended to wrap the entire application in Vue components within the master.jinja2 template. Howev ...

Saving the previous component's DOM in a React application

Understanding the Root.js File const Root = () => ( <HashRouter> <div> <Route exact path="/" component={Main}/> <Route path="/main/:page" component={Main}/> <Route path="/detail ...

Is it possible to log out a user in JavaScript by simply removing cookies?

Hey there, I currently have a node.js server running in the background which handles user login processes (I didn't create the backend code). app.use(function (req, res, next) { var nodeSSPI = require('node-sspi'); var nodeSSPIObj = n ...

Tips for incorporating fixed div columns within ngFor?

I need help implementing a design where I have a dynamic array of data that I want to display in 3 bootstrap columns per row like the following: <div class="row"> <div class="col-md-4"> <a>data</a> <a>data</a> ...

Update state within React components without impacting any other state variables

Imagine I have an object structured like this: person : { name : "Test", surname : "Test", age : 40, salary : 5000 currency : "dollar", currency_sign : "$", . . . } I am looking to achieve the following I will make ...

Postman is showing a 404 error message when trying to access an Express JS route that uses a POST request

Currently, I am working on creating APIs in Node.js with express and body-parser. While GET requests work fine using Postman, there seems to be an issue with POST requests as it consistently throws a 404 error saying Cannot GET / Express Version: @4.17.1 ...

"Is there a mysterious username lurking in the depths of cloud functions

I have a requirement to send a notification to a specific device, so I wrote this function and it seems to be working correctly. However, I am encountering an issue where the username is returning as undefined. Here are the logs output: Obtained data: a ...

JavaScript code to output CSS styled text: "echo"

Implementing anti-adblock on my site was necessary, as my bitcoin faucet relies on ads to function. I wrote some code to detect adblock on the client's browser: function TestPage() { if ($('.advertisement').height() == 0) var advertisement ...

Prevent URL changes for specific pages in React Router

Is there a way to maintain certain page URLs without changing them? I am aware that by using "MemoryRouter", I can navigate through different pages using history.push without altering the URL. However, I would like to change the URL for specific pages. Is ...

Issue with BootstrapVue b-table: selected rows are not saved when moving between pages with b-pagination

I implemented a b-table along with b-pagination in my Vue template: <b-table bordered hover responsive :items="items" :fields="fields" :sort-by.sync="sortBy" :sort-desc.sync="sortDesc" sort-icon-le ...

The @Mui datepicker seems to be causing some trouble with the react-hooks-form integration

Below is a code snippet where I showcase working and non-working sections (commented out). <Controller control={control} name="DOB" render={({ field }) => ( <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePic ...

Experimenting with applying jquery .slideDown() to multiple classes in order to create dynamic animations

I am facing an issue while using .slideDown() with multiple classes. I want only one class to toggle/dropdown at a time, but currently when I press the button, all classes show up instead of just the one I want to display. How can I achieve this? Here is ...

render target in three.js EffectComposer

When we utilize an EffectComposer, the scene is rendered into either composer.renderTarget2 or composer.renderTarget1. In a particular example, I came across this: renderer.render( scene, camera, composer.renderTarget2, true ); renderer.shadowMapEnabled ...

Issue with Webpack: Unable to import Vue from an instance stored in a different folder

Currently, I am in the process of integrating Vue.js into a Django project that is a multi-page application. The main objective is to divide the frontend code across the various apps within the project. Unfortunately, I have encountered an issue where I a ...

Invoke the parent's function within the Local-Registration component of VueJs

I have a Vue object: var app = new Vue({ el: '#my-id', data() { return { example: 1 } }, methods: { exampleMethos(data) { console.log('data', data); } }, ...

Utilize JavaScript array to filter, match, and perform calculations based on dates and names

I am working with the following dataset: const data = [ { "employee_name": "Employee A", "commission_date": "14/05/2018", "commission_price": 9000 }, { "employee_name": "Employee A", "commission_date": "17/05/2018", "commissi ...