Incorporating a vanilla JS library (Pickr) into a NuxtJS page component

Recently, I've been experimenting with integrating the Pickr JS library (specifically from this link: [) into my NuxtJS project.

To install it, I simply use NPM:

npm install @simonwep/pickr

In one of my NuxtJS pages - the create.vue page to be exact - here's what I did:

<template>
    <div>
        ..other HTML elements..
        <span class="color-picker"></span>
        ..other HTML elements..
    </div>
</template>

<script>
    import '@simonwep/pickr/dist/themes/classic.min.css';
    import Pickr from '@simonwep/pickr'

    export default {
        mounted() {
            // code below is taken from Github 
            const pickr = Pickr.create({
                el: '.color-picker',
                theme: 'classic', // or 'monolith', or 'nano'

                swatches: [
                    'rgba(244, 67, 54, 1)',
                    'rgba(233, 30, 99, 0.95)',
                    'rgba(156, 39, 176, 0.9)',
                    'rgba(103, 58, 183, 0.85)',
                    'rgba(63, 81, 181, 0.8)',
                    'rgba(33, 150, 243, 0.75)',
                    'rgba(3, 169, 244, 0.7)',
                    'rgba(0, 188, 212, 0.7)',
                    'rgba(0, 150, 136, 0.75)',
                    'rgba(76, 175, 80, 0.8)',
                    'rgba(139, 195, 74, 0.85)',
                    'rgba(205, 220, 57, 0.9)',
                    'rgba(255, 235, 59, 0.95)',
                    'rgba(255, 193, 7, 1)'
                ],

                components: {

                    // Main components
                    preview: true,
                    opacity: true,
                    hue: true,

                    // Input / output Options
                    interaction: {
                        hex: true,
                        rgba: true,
                        hsla: true,
                        hsva: true,
                        cmyk: true,
                        input: true,
                        clear: true,
                        save: true
                    }
                }
            });

        }
    }
</script>

However, upon navigating to the page where I imported the plugin, an error occurs:

https://i.sstatic.net/031aa.png

One thing that crosses my mind...

I suspect the error happens because it's trying to locate the

<span class="color-picker></span>
before it has been rendered yet. But I thought "mounted" runs after rendering the template. Am I misunderstanding something? How can I address this issue?

A Case of Vanilla JS Library Integration

Is there a standard way to incorporate a vanilla JS library as a plugin? I referred to the guide at https://nuxtjs.org/guide/plugins/ but couldn't quite grasp if my scenario fits in. Clearly, this isn't a Vue plugin but rather an ES6 one nested inside node_modules. So, how do we approach this to ensure access across all pages?

Odd Behavior Post-Server Restart

Peculiar observation - when I restart the server (CMD+C, npm run dev [both server and client compile successfully]), and proceed to visit http://localhost:3000/dashboard/ageRanges/create, the library functions flawlessly.

https://i.sstatic.net/vNXxf.png

Strangely, upon reloading the same page, the earlier error resurfaces.

https://i.sstatic.net/XhcBL.png

Any insights on why this might happen?

Answer №1

It appears that the Picker is directly accessing the window object, resulting in errors when importing in server-side mode.

To resolve this issue, a workaround is necessary. One potential solution is to move the import to a plugin that will only be loaded in client mode.

A similar approach was suggested in another answer regarding CKEditor plugins in Nuxt with SSR (https://stackoverflow.com/questions/55991788/how-to-add-plugins-of-ckeditor-in-nuxt-with-ssr/58141640#58141640), which tackles the same problem of the library accessing the window object.

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

The camera steadily advances in WebVR Cardboard using three.js technology, never stopping its forward movement

I've been experimenting with trying to create a smooth, continuous forward movement for the camera in a three.js/WebVR project, specifically with only a cardboard viewer needed. After much trial and error, I've discovered that the usual camera m ...

Unable to access property 'name' of null object

I'm currently learning how to build a local library app using Express with The Odin Project's tutorial. Below are the relevant parts of my code: In routes/catalog.js, I have this: router.get("/books", book_controller.book_list); In models/book. ...

What is the reason behind the TypeError thrown when attempting to assign to `NaN` or `undefined` in JavaScript

A.S.: The question pertains to the type of error rather than the phenomenon itself "use strict" results in a TypeError when system variables like NaN and undefined are modified. But why is it categorized as a TypeError instead of a SyntaxError? Edit: I ...

Steps to implement an image zoom function triggered by a button click

I'm working on a school project that requires me to use only html, css, and javascript for creating a website. Currently, I'm designing a landing page with a button that will navigate the user to another page. My goal is to have the background im ...

The true essence of Angular values only comes to light once the view has been updated

Here is the HTML code I am working with : <div class="container-fluid"> <div class="jumbotron" id="welcomehead"> <br><br><br><br><br><br><br><br><br><br> ...

"Troubleshooting issue: Unable to retrieve grid data from Google Sheets API v4 when integrated

I've implemented a function within a React component that retrieves JSON data from an API request and logs it: async function getAllSheets() { let response; try { response = await window.gapi.client.sheets.spreadsheets.values.batchGet( ...

The Ajax script is failing to retrieve search results

I am encountering an issue with my normal AJAX search functionality in which I need to retrieve data from a database when the form is submitted. The problem arises when trying to filter data between two specific dates using separate pages, it works fine bu ...

What is the best approach for filtering a nested array in this scenario?

Here is the response I am getting: let m = [ { name: 'Summary', subListExpanded: false, subList: [ ] }, { name: 'Upload', subListExpanded: false, subList: [ ...

The data stored in LocalStorage disappears when the page is refreshed

I'm facing an issue with the getItem method in my localStorage within my React Form. I have added an onChange attribute: <div className = 'InputForm' onChange={save_data}> I have found the setItem function to save the data. Here is ...

Conceal one element and reveal a different one upon submitting a form

On a web page, I want to hide the form upon submission (either by clicking or pressing enter) and display the results. However, this functionality does not seem to work when the Go web server is running. When I test the HTML file (without executing the Go ...

position the tooltip within the ample available space of a container in an angular environment

In my editor, users can create a banner and freely drag elements within it. Each element has a tooltip that should appear on hover, positioned on the side of the element with the most space (top, left, bottom, right). The tooltip should never extend outsid ...

The combination of VueJS and Webpack Dev Server is having trouble hot reloading URL subpaths

My application operates within the subdirectory http://localhost:8080/admin_suffix The variable suffix is an ENV variable that I can modify and define in a .env file. After starting the webpack dev server, accessing http://localhost:8080/admin_suffix fun ...

Remember a MySQL query using JavaScript

For quite some time, I've been on a quest to unveil the solution to this issue that seems relatively straightforward, yet continues to elude me. The crux of the matter is my desire to "recall" a functional mysql query. With an HTML button and a span ...

JavaScript code to dynamically change the minimum value of an input field when the page

How can I use JavaScript to change the minimum value onload? I tried the following code but it didn't work: <script type="text/javascript">$(document).ready(function(){ $("#quantity_5c27c535d66fc").min('10'); });</script> ...

Ways to retrieve the most recent message on WhatsApp Web

I'm currently developing a JavaScript script for WhatsApp Web that will automate responses to messages in a specific group. Here is a snippet of my code: console.log('WhatsappWeb On'); function sleep(num){ setTimeout(num); } var eve ...

Show a concealed dropdown menu within a CSS grid column utilizing clip-path styling

Working on a Django admin header that makes use of CSS grid to create two columns. I have added a JavaScript dropdown effect to the user icon for displaying options like "Change Password" and "Log Out". However, encountering an issue where the dropdown rem ...

Retrieve the values of elements

Is there a reliable way to retrieve an element's clientWidth and scrollWidth? I've tried using getCssValue, but it doesn't seem to work. $('.grid-header-col .title').getCssValue('scrollWidth') ...

Conceal portion in HTML until revealed

I am attempting to create 3 sections within a single HTML file using the <section id="id"> tag, and I want to be able to open each section by clicking a link in the header with <a href="#id">1</a>, and then close it when another section i ...

Is there a way to transform NextJS typescript files into an intermediate machine-readable format without having to build the entire project?

I need to deliver a Next.js project to my client, but I want to modify the TypeScript files so they are not easily readable by humans. The client will then build and deploy these files to their production environment. How can I achieve this? In summary, C ...

Is it considered inefficient to import every single one of my web components using separate <script> tags?

Currently, I am in the process of developing a website with Express + EJS where server-side rendering is crucial. To achieve this, I am utilizing web components without shadow dom. Each page type (home, post, page) has its own EJS view. For instance, when ...