Learn How to Write a Vue JS Wrapper Component

Published on by

Learn How to Write a Vue JS Wrapper Component image

A Vue “wrapper” component is a technique used to integrate a 3rd party plugin with Vue by wrapping it in a custom Vue component.

The wrapper technique means that you are likely bringing in a library like jQuery and a jQuery plugin. This combination seems to be the most ubiquitous, and it’s my personal preference when I want to use a jQuery plugin inside of a Vue application.

Let’s quickly cover an example of how we might build a wrapper component with a date range picker, which allows you to pick a start and an end date. For our example, we’ll use the Date Range Picker, which is a Bootstrap component that relies on jQuery and Moment.js.

In a simple example, you might use this component like so in a jQuery project:

$('input[name="daterange"]').daterangepicker();

In our case, we want to make it a Vue component that we can reuse, that will look something like this:

<date-range-picker @apply="onDateChange"></date-range-picker>

As you can gather from the jQuery example, the plugin expects to use a jQuery selector, so we need to replicate that in our component. To initialize the component, we could do something like the following in the Component’s mounted() lifecycle event:

mounted: function () {
this.$nextTick(function () {
window.$(this.$el).daterangepicker();
}
}

The component uses $nextTick to ensure that Vue has finished updating the DOM after data changes. As you can see, we are using the this.$el property, which is the root DOM element in the component. Unfortunately, our Vue component cannot react to the changes made.

It’s important to understand that your components shouldn’t reach outside of the component’s context. The best approach is to use the root element on the component using this.$el.

If we want to make our component react to changes made by the date range picker plugin, we need to hook up a jQuery event to respond to changes:

Vue.component('date-range-picker', {
template: '#date-range-template',
props: {
startDate: {
default: function () {
return moment().subtract(30, 'days');
}
},
endDate: {
default: function () {
return moment();
}
}
},
data: function () {
return {
start: this.startDate,
end: this.endDate
};
},
computed: {
dateRange: function () {
var start = moment(this.start);
var end = moment(this.end);
 
return start.format('LL') + ' - ' + end.format('LL');
}
},
mounted: function () {
var vm = this;
this.start = moment(this.start);
this.end = moment(this.end);
this.$nextTick(function () {
var options = {
startDate: this.start,
endDate: this.end,
alwaysShowCalendars: true
};
 
window.$(this.$el)
.daterangepicker(options)
.on('apply.daterangepicker', function (e, picker) {
vm.$emit('apply', picker.startDate, picker.endDate);
vm.start = picker.startDate;
vm.end = picker.endDate;
});
});
}
});

You can see that we’ve added a bunch of code to the component, but first look at the updated mounted() call. Now we’ve provided a on('apply.daterangepicker') event handler which emits an apply event with the start and end dates. Next, the callback sets the new start and end dates on the component instance.

We also provide some props for start and end date, with default values which set the date range over the last 30 days.

Here’s the accompanying template for the component:

<script type="text/x-template" id="date-range-template">
<div class="btn-group">
<a class="btn btn-default btn-rounded calendar-picker"
data-toggle="collapse"
aria-expand="true"
>
<span class="date-range-label">{{ dateRange }}</span>
<span class="caret"></span>
</a>
</div>
</script>

I’ve used a Bootstrap button group, but you could also make an additional component for a form input. In my case, I wanted the date range picker to be a button that was clickable, but the user couldn’t edit the date range via a form input.

At this point, we have a component that emits an event when the date range is updated. In the parent, we can listen to that event by defining an event attribute:

<date-range-picker @apply="onDateChange"></date-range-picker>

A simple event handler example might look like the following:

var app = new Vue({
el: '#app',
data: {
start: null,
end: null
},
methods: {
onDateChange: function (start, end) {
this.start = start;
this.end = end;
}
}
});

Let’s add some more options to the wrapper component to expose more functionality from the underlying date range plugin. Here’s a complete example:

Vue.component('date-range-picker', {
template: '#date-range-template',
props: {
showRanges: {
type: Boolean,
default: false
},
startDate: {
default: function () {
return moment().subtract(30, 'days');
}
},
endDate: {
default: function () {
return moment();
}
},
minDate: {
default: false
},
opens: {
default: 'right'
},
maxDate: {
default: false
},
autoApply: {
default: false
},
},
data: function () {
return {
start: this.startDate,
end: this.endDate
};
},
computed: {
dateRange: function () {
var start = moment(this.start);
var end = moment(this.end);
var today = moment();
if (
start.format('LL') === end.format('LL') &&
today.format('LL') === start.format('LL')
) {
return 'Today';
} else if (start.format('MM-DD-YYYY') === end.format('MM-DD-YYYY')) {
return start.format('LL');
}
 
return start.format('LL') + ' - ' + end.format('LL');
}
},
mounted: function () {
var vm = this;
this.start = moment(this.start);
this.end = moment(this.end);
this.$nextTick(function () {
var options = {
opens: this.opens,
startDate: this.start,
endDate: this.end,
autoApply: this.autoApply,
alwaysShowCalendars: true
};
 
if (this.minDate) {
options.minDate = this.minDate;
}
if (this.maxDate) {
options.maxDate = this.maxDate;
}
 
if (this.showRanges) {
options.ranges = {
Today: [moment(), moment()],
Yesterday: [
moment().subtract(1, 'days'),
moment().subtract(1, 'days')
],
'Last 7 Days': [
moment().subtract(6, 'days'),
moment()
],
'Last 30 Days': [
moment().subtract(30, 'days'),
moment()
],
'This Month': [
moment().startOf('month'),
moment().endOf('month')
],
'Last Month': [
moment().subtract(1, 'month').startOf('month'),
moment().subtract(1, 'month').endOf('month')
]
};
}
 
window.$(this.$el)
.daterangepicker(options)
.on('apply.daterangepicker', function (e, picker) {
vm.$emit('apply', picker.startDate, picker.endDate);
vm.start = picker.startDate;
vm.end = picker.endDate;
});
});
}
});

We’ve added a bunch more options, although these options might not be 100% of the available options the plugin provides. I prefer to grab the options I need and add more as I need them in a project.

Based on the passed component props, you can customize the functionality and options available to the plugin, which makes this wrapper component super flexible and only exposes the options that you want to expose, allowing you to isolate or disable some options that you don’t want to support.

The dateRange computed property will now more intuitively display the date range. If the start and end date range are today, the label will output “Today.” If the date range spans only one day, it just shows one date. And by default, the UI will display the start and end date.

Here’s a more complete example of how you might use the component:

<date-range-picker
@apply="onDateChange"
:start-date="startDate"
:end-date="endDate"
:max-date="defaultEndDate"
min-date="01-01-2017"
opens="left"
>
</date-range-picker>

You can define a max date, the default start, and end dates, and the minimum date that can be selected. Last, you can configure which way the date range picker opens.

Learn More

Check out the complete working example (JS Bin) using ES5. You can quickly adapt the component to ES6.

In this component example, you learned how to wrap a jQuery plugin by using the root this.$el DOM element in a component to initialize a plugin when the component is mounted. You also learned how you need to hook into the plugin to emit data to a parent component.

The official Vue documentation has a Wrapper Component Example, which demonstrates using the popular Select2 jQuery plugin in a wrapper Vue component with v-model to bind a custom wrapper component.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Forge
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with Vue and Livewire stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Audit MySQL Databases in Laravel With the DB Auditor Package image

Audit MySQL Databases in Laravel With the DB Auditor Package

Read article
The Ability to Prevent Destructive Commands From Running is Coming to Laravel 11 image

The Ability to Prevent Destructive Commands From Running is Coming to Laravel 11

Read article
Configuring Laravel With Additional Environment Files image

Configuring Laravel With Additional Environment Files

Read article
Real Time Command Line Monitoring With Laravel Top image

Real Time Command Line Monitoring With Laravel Top

Read article
A New Validation Rule and the Ability to Manually Fail a Command in Laravel 11.8 image

A New Validation Rule and the Ability to Manually Fail a Command in Laravel 11.8

Read article
New Array Find Functions in PHP 8.4 image

New Array Find Functions in PHP 8.4

Read article