Guide on incorporating vanilla JavaScript into a personalized Vue component

I'm currently working on incorporating a basic date-picker into a custom Vue component. Since I am not utilizing webpack, I want to avoid using pre-made .vue components and instead focus on understanding how to incorporate simple JavaScript into Vue.

For guidance, I have been referring to this official Vue tutorial

I also came across this codepen example, but I am struggling to get the date picker to display properly.

You can view my current progress on jsfiddle:

HTML:

<div class="app">
  <datepicker id='date-elem'></datepicker>
</div>

app.js:

Vue.component('date-picker', {
  extends: Flatpickr,
  mounted () {
    this.Flatpickr(date-elem, {})}
})

What is the best way to integrate vanilla JavaScript into a Vue component without relying on .vue files or webpack?

Answer №1

It seems there are some misunderstandings in your approach. To create a basic component, you can follow these steps.

In Vue, the typical way to incorporate an external JavaScript library is by creating a wrapper component. This component will manage all the interactions with the external library. For example, if you want to utilize Flatpickr, according to the documentation, you need to use new Flatpickr(element, options). You can achieve this within the mounted event by passing this.$el, which references the root element of the Vue component.

Vue.component('date-picker', {
    template: "<input type='text'>",
    mounted () {
        new Flatpickr(this.$el, {})
    }
})

You can find the updated fiddle here.

However, the current component has limited functionality as it only allows date selection. To enable the selected date to be accessed from outside the component using v-model, you can extend the component as follows:

Vue.component('date-picker', {
    props:["value"],
    data(){
        return {
            selectedDate: this.value
        }
    },
    template: "<input type='text' v-model='selectedDate' @input='onInput'>",
    methods:{
        onInput(){
            this.$emit('input', this.selectedDate)
        }
    },
    mounted () {
        new Flatpickr(this.$el, {})
    }
})

Now, you can use the component in this manner:

<date-picker v-model="selectedDate"></date-picker>

The selectedDate variable will capture the chosen date.

You can refer to this fiddle for demonstration.

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

Is there a way to determine the duration that a click was held down for?

When triggering an onClick event, I want to determine whether it was a single click or if the mouse button was held down for some time before releasing. This way, I can call the myTest() function within onClick="myTest()", which will log "mouse was click ...

Error handling in angularJS can be quite challenging at times,

Currently, I am experimenting with AngularJS to develop an application, and I have encountered a challenge related to the $scope context. This is the main file of my app: var app = angular.module('app', [ 'matchCtrl', &apos ...

Pass the callback function `cb_func` as a parameter to the `foobar` function when calling it in the `onclick`

I have an element that I want to trigger an onclick event with a callback function. Here is the code snippet: function cb_func() { alert("hello world!"); } function foobar(i, cb) { // do something if (cb != undefined) cb(); } onclic ...

Using conditional logic to check if a column cell is empty

I need help writing a Javascript function that will loop through rows in a table and only change the background color of cells in "column2" if they are empty. My current code is not working as expected, as it colors all rows instead of just those with empt ...

The aggregation pipeline in nodeJS with mongoDB is failing to return any results, returning an empty array instead

Currently, I am enrolled in Jonas Schmeddtman's Node.js course where I am working on developing a tour App. However, I have encountered an issue where sending a request via Postman on the specified route results in an empty array instead of the expect ...

Run a function upon clicking a button in JavaScript

Could someone please help me figure out what I am doing incorrectly in the code below? I am attempting to trigger a function when a button is clicked. The HTML: <button id="btn1">Press me!</button> <input type="button" id="btn2" value="Pr ...

Access a file from a specified route within Express

Recently, I created a custom Node module that requires a configuration file in CSV format. My goal is to implement this module within an Express Route module; however, I am encountering difficulties related to the loading of the configuration file. Should ...

Can an image map be utilized within an <a> element?

I am attempting to implement an image map within an <a> tag. It seems to be functioning correctly in Chrome, but I am encountering issues with it not working in Internet Explorer. Is it acceptable to use an image map in an <a> tag? Below is th ...

What is the best way to pass and save information across different routes in Express using Node.js?

Let's delve into the specific functionalities I envision for my server. Essentially, my project involves user registration and login processes. The URLs for these routes are as follows - localhost:3000/login and localhost:3000/register Upon successf ...

live PHP recording of data moving between tables

As a beginner, I am working on a project to organize groups of people on the screen using PHP code. I have managed to list Distribution Lists, Member Lists, and People, but I lack experience in this area. Can anyone provide some guidance on how to proceed? ...

How can I assign a value other than a string to a placeholder or vue property?

As I develop a content management system using Nuxt and Pug/Jade, I am looking for an efficient way to create a list of input fields for users to enter information. My idea is to use the v-for directive to render the list and dynamically set the value and ...

Creating modules or classes in ExpressJS

I am in the process of defining a modules/class that will contain a list of methods. Each method will have an instance of a service such as loggers, promises, etc. What is the best way to ensure clean code while implementing this? Currently, my code incl ...

Collision detection in Physisjs with Three.js PointerLockControls is an essential feature for creating

I am currently working on a project using Three.js with PointerLockControls. My goal is to implement collision detection for the player in order to enhance the overall experience. To achieve this, I have created a new Physijs cylinder object and passed it ...

When activated, JavaScript is producing an undefined response

This is a function with the following designer code. I have made updates to include the latest answer. function OnClientLoBChecked(sender, args) { var ChkBoxLOB = document.getElementById("<%= cbFLoB.ClientID %>"); var ChkBoxDis = document ...

Having trouble accessing data from MongoDB using Node.js and Express

Looking to retrieve data from Mongo DB using Node JS and Express JS? After creating a mongoose schema and exporting the module, you may encounter an issue where running the function returns an empty JSON object. Take a look at the code snippets below: Thi ...

Display or conceal HTML content based on the input's property type

Looking to toggle the visibility of an icon on my input based on the prop type. If the type is set to password, the icon will be displayed for toggling between visible and hidden password; if the type is not password, the icon should be hidden by setting ...

What is preventing me from updating specific packages to the latest version using vue ui / npm?

Currently, I am utilizing Vue CLI and have been using the command vue ui to facilitate updating npm packages. Upon executing this command, I encountered a particular screen as displayed in the following image: https://i.stack.imgur.com/6cDlI.png I am see ...

The HTML form submission button fails to submit the form and instead just refreshes the page

I'm struggling to get the save button working on my Chrome Extension settings page. The .click() event doesn't seem to be activating at all. I've included my code below. Should I use the commented out button instead (see below)? HTML <! ...

Displaying only the records that are associated with the user using Laravel's relationships

After developing a system using Laravel and Vue.js, I have multiple users with access to the system. My goal is to ensure that each user can only view data related to their team. The system includes workers, teams, and jobs. When a worker is created, a cor ...

Is it possible to change the src attribute after the page has loaded and execute it

A. I'm trying to figure out how to dynamically change the src attribute of an image using JavaScript after the page has loaded. <img src="http://example.com/image.png" /> to <img src="http://domain.com/different.jpg" /> B. Another questi ...