2

I am trying to use Vanilla JS Datepicker in a Vue3 project but unsure how to correctly set it up. As per the docs (which I realise don't specifically relate to Vue) I have installed the package:

npm install --save-dev vanillajs-datepicker 

In the template:

<input type="text" name="foo" />

The script:

import { Datepicker } from "vanillajs-datepicker";


mounted() {
    const elem = document.getElementById("foo");
    const datepicker = new Datepicker(elem, {
      // ...options
    });
},

I am getting the error:

error 'datepicker' is assigned a value but never used

UPDATE

<input type="text" ref="foo" />

new Datepicker(this.$refs.foo, {
  // ...options
});

And all is working.

1 Answer 1

3

Update

This is a working solution that I achieved.
I find it a bit messy already, not sure that I would use that one but it works let's say.

<script setup>
import { onMounted } from "vue";
import "../../node_modules/vanillajs-datepicker/dist/css/datepicker.min.css";
import Datepicker from "vanillajs-datepicker/Datepicker";

onMounted(() => {
  const elem = document.querySelector('input[name="date"]');
  const datepicker = new Datepicker(elem);
  console.log("picker", datepicker);
});
</script>

<template>
  <input type="text" name="date" />
</template>

That error is related to ESlint, what it means is that your variable datepicker is not used down the code (plenty of similar questions on this website that you can look for if you need more details).

If you use a console.log(datepicker) for example, it will disappear.

You can also disable that rule or mark it as a warning.

As for elem, you should use a template ref rather: https://vuejs.org/guide/essentials/template-refs.html#template-refs
It will produce the same result as a document selector but is a better practice since you're using an SPA.

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

3 Comments

Perfect. It actually works if I just remove the definition of datepicker. Good point about $refs. Thanks once again - a great help.
@RGriffiths I've shared a Composition API example. Not exactly sure why it doesn't work with refs there, I don't have a lot of experience with CAPI.
Nice one. Good to see the other ways of doing it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.