What is the best approach for developing an npm package containing multiple Vue directives? Should each directive have its own separate package, or should they

While I have successfully created an npm package by exporting a single vue directive in the src/index.js file, I am now faced with the challenge of creating a package that allows for the use of multiple vue directives. Unfortunately, I have been unable to export two vue directives in the same index.js file.

export default Vue.directive('directive1', {
  inserted: function (el, binding, vnode) {
    el.addEventListener('mouseup', (e) => mouseup(e, el, _data))
    el.addEventListener('mousedown', (e) => mousedown(e, el, _data))
    el.addEventListener('mousemove', (e) => mousemove(e, el, _data))
    setDraggerOffset(el, _data)
  }
})

export default Vue.directive('directive2', {
  inserted: function (el, binding, vnode) {
    el.addEventListener('mouseup', (e) => mouseup(e, el, _data))
    el.addEventListener('mousedown', (e) => mousedown(e, el, _data))
    el.addEventListener('mousemove', (e) => mousemove(e, el, _data))
    setDraggerOffset(el, _data)
  }
})

Answer №1

If you are looking to export two defaults, keep in mind that using a default allows you to easily retrieve the value with a simple import statement like

import MyPack from 'path/to/package'
. Make sure to export constants and destructure when importing to ensure smooth functionality. For more information, check out this helpful resource here

In your package:

export const vD1 = Vue.directive('directive1', {
  ...
})

export const vD2 = Vue.directive('directive2', {
  ...
})

During your import process:

import { vD1, vD2 } from 'path/to/package';

Answer №2

Refer to the Vue Guide: Writing one plugin for guidance on developing directives and allowing users to activate specific directives using the 2nd parameter=options.

For example, consider the demo below (assuming exporting myDirectives and enabling only directive1):

let myDirectives = {}
let _defaultDirectives = ['directive1', 'directive2']
myDirectives.directive1 = {
  inserted: function (el, binding, vnode) {
    el.addEventListener('mouseup', (e) => mouseup(e, el, _data))
    el.addEventListener('mousedown', (e) => mousedown(e, el, _data))
    el.addEventListener('mousemove', (e) => mousemove(e, el, _data))
    console.log('directive1', `setDraggerOffset(el, _data)`)
  }
}

myDirectives.directive2 = {
  inserted: function (el, binding, vnode) {
    el.addEventListener('mouseup', (e) => mouseup(e, el, _data))
    el.addEventListener('mousedown', (e) => mousedown(e, el, _data))
    el.addEventListener('mousemove', (e) => mousemove(e, el, _data))
    console.log('directive2', `setDraggerOffset(el, _data)`)
  }
}

myDirectives.install = function (Vue, options) {
  let selectedDirectives = (options && options.directives) || _defaultDirectives
  selectedDirectives.forEach((directive) => 
    Vue.directive(directive, this[directive])
    // this[directive + 'Definition'] = Vue.directive(directive, this[directive])
  )
}

// export default myDirectives

// Vue.use(myDirectives) // default option is register both directive1 and directive 2
Vue.use(myDirectives, {directives: ['directive1'] }) // register directive1 only

// console.log('Definition', myDirectives.directive1Definition, myDirectives.directive2Definition)

new Vue({
  el: '#app'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <span v-directive1></span>
  <span v-directive2></span>
</div>

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

JQuery loader & amazing animations

I have implemented the wow.js plugin along with a jQuery preload tutorial from here. Although the preloader works fine, I am facing an issue where the animation by wow.js starts before all the elements on the page are preloaded. I am looking to modify my ...

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 ...

Using JavaScript to detect the Facebook like button on a webpage

I am currently developing an application for Facebook using HTML and Javascript. My goal is to be able to detect when a user clicks the "Like" button on my company's Facebook page without needing to embed a separate "Like" button within my app itself. ...

Issue with AngularJS expression not functioning as expected in Chrome for setting input type to "file"

I have encountered a strange bug while working on an Angular form builder application. The issue arises in Chrome when I try to dynamically set the input type based on a variable. Surprisingly, this method works perfectly for all input types except "file", ...

React encountered an error: Unable to destructure the property 'id' of '_ref' as it has been defined

After spending several hours trying to solve this issue, I am completely stuck. The console shows that the patch request successfully updates the information, but then my map function breaks, leading to a blank page rendering. Here is the problematic comp ...

Definitions that are displayed dynamically when hovering over a particular element

I am seeking a way to implement popup definitions that appear when a div is hovered over. My website showcases detailed camera specifications, and I want users to see a brief definition when they hover over the megapixel class called '.mp'. One o ...

Troubleshooting: Unable to preview Facebook Page plugin

When I visit the Facebook developer site to get the code for a Facebook page plugin, I use this link. The preview feature works perfectly with pages like "facebook.com/Nike", but when I try it with my own page, "facebook.com/BargainHideout", it doesn&apos ...

AngularJS - Filter out items from ng-repeat that match specific string criteria

After successfully cleaning up an external JSON URL feed by removing unnecessary special characters through a filter in my AngularJS code, I am now faced with the challenge of filtering out specific items from an ng-repeat based on a certain string. angul ...

Leveraging the arguments object within function declarations

Could someone explain why the foo function functions properly? function foo (x,y) { return arguments.length; } However, when I call the boo function with arguments, it returns an error saying undefined is not a function. function boo (c,d) { return ...

"Exploring the Power of TypeScript Types with the .bind Method

Delving into the world of generics, I've crafted a generic event class that looks something like this: export interface Listener < T > { (event: T): any; } export class EventTyped < T > { //Array of listeners private listeners: Lis ...

HTML embedded content is not appearing on the React webpage

I'm attempting to incorporate GoFundMe donation buttons into a React page, but unfortunately, they aren't displaying on the screen. const Donation = () => { return ( <div> <div className="gfm-embed" d ...

Sticky header in React data grid

Is there a way to implement a sticky header for a data grid in react? I have tried various methods but haven't been able to figure it out. Any suggestions would be appreciated. You can find my code sandbox example here. #react code export const Styl ...

Vue SSR combines the express server with the vue app, allowing the application to be launched directly from the build dist directory, which can then be transferred to a hosting server for

After creating a Vue SSR application, I found that most resources only cover running the app in a development environment. Unfortunately, they do not provide guidance on launching the application in a production environment. In contrast, when I developed ...

Sending text from a Tinymce textarea using Laravel 4.2

I am currently facing an issue with a form that includes a tinymce textarea, allowing users to edit text and save it into a database with HTML tags for display on their profile. The problem arises when Laravel 4.2 escapes the HTML tags, making it difficult ...

Extending a Typescript class from another file

I have a total of three classes spread across three separate .ts files - ClassA, ClassB, and ClassC. Firstly, in the initial file (file a.ts), I have: //file a.ts class ClassA { } The second file contains: //file b.ts export class ClassB extends Class ...

Effects of incorporating unnecessary packages on Vue.js performance

In my Vue.js component, I have imported the module useI18n from "vue-i18n" but have not utilized it anywhere within the component. Concerned about how this could affect performance, particularly in terms of bundle size and load times. Will importing a mod ...

Choose the option for overseeing safaris

Hello there! I need some help with Safari. Can you please guide me on how to disable the arrows? https://i.stack.imgur.com/1gzat.png ...

Custom pagination for next/previous links in Django REST framework

When it comes to backend operations, I have integrated the PageNumberPagination as the DEFAULT_PAGINATION_CLASS. Since I am utilizing vue.js along with fetch, there is no need for me to include the entire URL structure provided by django-rest-framework: " ...

JavaScript: Automatically retrieving the if else function

I need help automating the calculation of the number of days a person worked based on their "in-time" and "out-time". I've tried to implement this in my JS code, but it's not working as expected. HTML <fieldset> In-Time: <input clas ...

verdaccio Encountered Issue: 413 Payload Exceeds Limit - PUT request data size is too large

Recently, I utilized Verdaccio, which is a lightweight private npm proxy registry developed in Node.js Every time I attempted to publish my code to Verdaccio, an error occurred: The log file contains the following details: 15 notice === Tarball Details = ...