I wrote in a previous article the importance of Web Components and how to make them work with React. Today, I’m focusing on a Vue example with a Web Component input element.
Fortunately, Vue fully supports Web Components according to custom-elements-everywhere.com but I faced a small inconvenience while using v-model directive with an input element.
V-model is a built-in directive in Vue that makes data binding easier with less code.
The code below:
Is the same as:
Currently, we can’t use v-model in a Web Component but we can create our own custom directive to make it behave the same way across all custom elements!
For simplicity purposes, I’m using Wired Elements for the Web Components example. Wired Elements are a set of common UI elements with a hand-drawn, sketchy look. The library uses LitElement for creating Web Components.
- Create Vue App
- Install Wired Elements
- Import Input Element
- Create a custom directive
- Test input element with the custom directive
1. Create Vue App:
Install Vue CLI and create a new project.
npm install -g @vue/cli @vue/cli-service-global
vue create vue-custom-v-model-example
2. Install Wired Elements:
Full documentation on Wired Elements is available on their main repository
npm i wired-elements
3. Import Input Element:
In this section, we will add a Wired Input Element and show how the v-model won’t work the way it usually does with the native input element.
Quick summary of the code above:
- Imported “wired-input”
- Created a new “txtValue” data to use in v-model
- Print out the “txtValue” on the screen as we are typing
Now as expected, when typing, nothing is printed:
4. Create a custom directive:
Let’s create a new directive and call it “custom-model.js”. The directive will listen to the input event and update the binding value.
Here are some details of what we did in the code above:
- In line 4, we are using the “bind” hook function (when the directive is first bound to the element)
- In line 6, we are accessing the context data from “vnode” object to update the binding value in the “inputHandler” function.
- Line 7, simply add an event listener to the element
5. Test input element with the custom directive
Now that we have the directive ready, let’s apply it to the web component.
First, let’s update App.vue to use the new directive:
Here is a demonstration of the final working code:
You can access the full repository here. I hope you enjoyed learning from this article and if you have any questions, please leave a comment below.
Originally published at https://muhimasri.com on April 10, 2021.