Building a WordPress Plugin with Vue

Building a WordPress Plugin with Vue

<strong>In this tutorial, we’ll learn how to integrate [Vue.js](</strong><a href="https://vuejs.org/v2/guide/index.html#What-is-Vue-js)" target="_blank"><strong>https://vuejs.org/v2/guide/index.html#What-is-Vue-js)</strong></a><strong> with a WordPress plugin to provide a modern UI experience to our WordPress users.</strong>

In this tutorial, we’ll learn how to integrate [Vue.js](https://vuejs.org/v2/guide/index.html#What-is-Vue-js) with a WordPress plugin to provide a modern UI experience to our WordPress users.

Vue.js is a very popular progressive JavaScript library for building modern and rich user interfaces similar to Angular and React in terms of popularity, performance and component-based architecture. We’ll dive into the entire process of building a very simple WordPress plugin with a Vue interface that interacts with the WordPress REST API through the JavaScript Fetch API.

We’ll create a shortcode that will allow us to add a latest published posts widget in our WordPress website. The UI of the widget is a Vue app which fetches the latest published posts via the /wp-json/wp/v2/posts?filter[orderby]=date WP-API endpoint.

This tutorial assumes some familiarity with Vue.js. We’ll see how to create a Vue instance, use life-cycle hooks like mounted(), and also the JavaScript Fetch API to interact with the WordPress REST API.

Creating a WordPress Plugin

In this section, we’ll see how to create a WordPress plugin that registers a shortcode in a few steps.

Create a Folder in wp-content/plugins

Let’s start by creating the back-end part of our plugin. Plugins live inside the wp-content/plugins folder. Navigate to this folder inside your WordPress installation folder and create a sub-folder for your plugin. Let’s call it vueplugin:

cd /var/www/html/wp-content/plugins
mkdir vueplugin

Inside your plugin folder, create a vueplugin.php file and add the initial content:

<?php
/*
Plugin Name: Latest Posts
Description: Latest posts shortcode
Version: 1.0
*/

These comments are used as meta information for the plugin. In our case, we simply provide a plugin name, description and version.

If you visit the plugins page in the admin interface you should be able to see your plugin listed:


Creating a Shortcode

Shortcodes are used via WordPress plugins to enable users to add content to posts and pages. To register a shortcode you need to add the following minimal code in your plugin file:

function handle_shortcode() {
return 'My Latest Posts Widget';
}
add_shortcode('latestPosts', 'handle_shortcode');

We’re registering a shortcode named latestPosts.

WordPress provides the built-in add_shortcode() function to create the shortcode in your WordPress plugin. The function takes a name as the first parameter and the handler function that processes your shortcode logic and returns an output as a second parameter.

At this point, we’re only returning a static string from our shortcode, but shortcodes are more useful when used to insert dynamic content.

Now, let’s activate the plugin from the admin interface by clicking on the Activate link below the plugin name:

You can use a shortcode by enclosing it in square brackets — that is, [SHORTCODE_NAME]. The text inside the brackets is the name we passed as the first parameter to the add_shortcode() function. It gets replaced by the output returned by the PHP function passed as the second parameter.

To test if our shortcode is successfully registered, we can create a new post and add [latestPosts] in the post content:

You should see My Latest Posts Widget sentence rendered:

Now, instead of displaying the static My Latest Posts Widget string, let’s display the latest posts using Vue.js.

Integrating Vue.js with a WordPress Plugin

The Vue docs lists different methods of using Vue.js. The easiest one is using a <script> tag to include the library script, which is also the most straightforward way to integrate Vue.js with WordPress.

You can integrate a Vue app with WordPress in a few easy steps:

  • First, you need to add a DOM element in WordPress (e.g. via a shortcode) where you can mount the Vue app.
  • Next, you need to enqueue the Vue library script.
  • Finally, you need to create a Vue app inside a separate JavaScript file and enqueue it.

Unlike the traditional approach of using WordPress, using Vue.js will allow you to add better interactivity and user experience. Instead of needing to constantly reload the current page, users can interact with the page and have the interface dynamically updated. Apps created with Vue.js are called SPAs, or single page applications. But in our case, instead of creating a complete SPA, we’ll only use Vue.js to create a simple widget that can be used to render information in a small part of your page (such as in the sidebar). Think of a widget created with Vue.js as a sort of a small SPA.

Let’s start by enqueueing the Vue library in WordPress. We need to add another function to our plugin which handles the enqueueing of the Vue library:

function enqueue_scripts(){
global $post;
if(has_shortcode($post->post_content, "latestPosts")){
wp_enqueue_script('vue', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js', [], '2.5.17');
}
}

We first check if we’re displaying a post that includes our latestPosts shortcode, then we enqueue the Vue script using the wp_enqueue_script() function.

You can check if the script is included by visiting your post source code:

Next, go back to the handle_shortcode() function and change it to include a <div> where we can render a Vue app:

<div id="mount"></div>

Next, create a latestposts.js file inside your plugin folder and add the following code to create a Vue instance:

( function() {
var vm = new Vue({
el: document.querySelector('#mount'),
mounted: function(){
console.log("Hello Vue!");
}
});
})();

We create a new Vue instance with the Vue() function, which is the first step to start the Vue application.

When creating the Vue instance, you also need to provide an options object, which allows you to provide different options for building your Vue app.

In our example, we use the el property to provide the Vue instance an existing DOM element to mount on. This can be either a CSS selector or an actual HTMLElement. In our case, we use document.querySelector('#mount') to get the HTML element of the <div> with the #mount ID.

We also use the mounted property to provide a function that will be called after the instance has been mounted. At this point, we only log a Hello Vue! string on the console.

You can also browse the full list of the available options in the API reference.

Next, just like the Vue library, you need to enqueue this file. Inside the enqueue_scripts() function add the following code:

wp_enqueue_script('latest-posts', plugin_dir_url( FILE ) . 'latest-posts.js', [], '1.0', true);

The plugin_dir_url() built-in function is used to get the absolute URL of a file. FILE is a constant that gives you the file-system path to the current PHP file. This will allow us to get the absolute path of the latest-posts.js file without using any hardcoded URLs that could be changed on a different system.

At this point you should see the Hello Vue! string on the browser’s console:

And you should also see the latest-posts.js script included in the source code of a post that contains the shortcode.

Next let’s change the plugin to render the previous My Latest Posts Widget string, but this time from Vue. In your Vue instance, include the template property with whatever HTML code you want to render:

 var vm = new Vue({
el: document.querySelector('#mount'),
template: "<h1>My Latest Posts Widget</h1>",
mounted: function(){
console.log("Hello Vue!");
}
});

Now, let’s fetch and render the latest posts using the fetch API.

In the Vue instance, add a data property with a posts array which will hold the fetched posts:

 var vm = new Vue({
el: document.querySelector('#mount'),
data: {
posts: []
},

Next, let’s include the code to fetch the latest posts in the mounted life-cycle event that gets fired when the component is mounted on the DOM:

 var url = '/wp-json/wp/v2/posts?filter[orderby]=date';
fetch(url).then((response)=>{
return response.json()
}).then((data)=>{
this.posts = data;
})

We call the JavaScript fetch() method which returns a Promise. After successfully resolving the Promise, we assign the data to the posts array.

Finally, add the template property:

template: &lt;div&gt;&lt;h1&gt;My Latest Posts&lt;/h1&gt;   &lt;div&gt;     &lt;p v-for="post in posts"&gt;       &lt;a v-bind:href="post.link"&gt;{{post.title.rendered}}&lt;/span&gt;&lt;/a&gt;     &lt;/p&gt;   &lt;/div&gt; &lt;/div&gt;,

We use the Vue v-for directive to loop through the posts and display the title.rendered and the link properties of each post.

This is a screenshot of the result for me.

In your case, it may look different depending on your active theme and the posts you have in your WordPress website.

If you click on the post title you should be taken to the post page.

We can add more features to our widget, such as real-time data fetching, so the user doesn’t need to reload the page to retrieve the latest published posts. We can achieve this by continuously polling the WP-API endpoint using the JavaScript setInterval()method.

First, move the code that fetches the posts in its own method:

 var vm = new Vue({
/.../

methods:{

fetchPosts: function(){
var url = '/wp-json/wp/v2/posts?filter[orderby]=date';
fetch(url).then((response)=>{
return response.json()
}).then((data)=>{
this.posts = data;
console.log(this.posts);
});
}
},

We use the methods property of the Vue instance to add custom methods in our Vue instance. You can then access these methods directly on the instance via this.

Next, in the mounted() function, add the following code to fetch posts every five seconds:

 var vm = new Vue({
/.../
mounted: function() {
console.log("Component is mounted");

this.fetchPosts();
setInterval(function () {
this.fetchPosts();
}.bind(this), 5000);
}

You can test this by opening the WordPress admin interface in another browser’s tab and adding a new post. You should see your Vue widget updated with a new post without manually refreshing the page.

Conclusion

In this tutorial, we’ve seen how to create a WordPress plugin that makes use of the Vue.js library. We’ve created a shortcode that can be used to display a Vue component in your posts and pages that fetches and displays the latest posts every five seconds. This was achieved via polling the WordPress REST API using the setInterval() method.

Learn more

☞ Learn by Doing: Vue JS 2.0 the Right Way

☞ Vue.js 2 Essentials: Build Your First Vue App

☞ Getting started with Vuejs for development

☞ Horizontal Feed Component with Sass and VueJs 2

☞ Learn Vue 1 JS introduction to simple reactive JavaScript

10 Best Vue Icon Component For Your Vue.js App

10 Best Vue Icon Component For Your Vue.js App

In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.

Icons are the vital element of the user interface of the product enabling successful and effective interaction with it. In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.

1. Animated SweetAlert Icons for Vue

A clean and simple Vue wrapper for SweetAlert's fantastic status icons. This wrapper is intended for users who are interested in just the icons. For the standard SweetAlert modal with all of its bells and whistles, you should probably use Vue-SweetAlert 2

Demo: https://vue-sweetalert-icons.netlify.com/

Download: https://github.com/JorgenVatle/vue-sweetalert-icons/archive/master.zip

2. vue-svg-transition

Create 2-state, SVG-powered animated icons.

Demo: https://codesandbox.io/s/6v20q76xwr

Download: https://github.com/kai-oswald/vue-svg-transition/archive/master.zip

3. Vue-Awesome

Awesome SVG icon component for Vue.js, with built-in Font Awesome icons.

Demo: https://justineo.github.io/vue-awesome/demo/

Download: https://github.com/Justineo/vue-awesome/archive/master.zip

4. vue-transitioning-result-icon

Transitioning Result Icon for Vue.js

A scalable result icon (SVG) that transitions the state change, that is the SVG shape change is transitioned as well as the color. Demonstration can be found here.

A transitioning (color and SVG) result icon (error or success) for Vue.

Demo: https://transitioning-result-icon.dexmo-hq.com/

Download: https://github.com/dexmo007/vue-transitioning-result-icon/archive/master.zip

5. vue-zondicons

Easily add Zondicon icons to your vue web project.

Demo: http://www.zondicons.com/icons.html

Download: https://github.com/TerryMooreII/vue-zondicons/archive/master.zip

6. vicon

Vicon is an simple iconfont componenet for vue.

iconfont
iconfont is a Vector Icon Management & Communication Platform made by Alimama MUX.

Download: https://github.com/Lt0/vicon/archive/master.zip

7. vue-svgicon

A tool to create svg icon components. (vue 2.x)

Demo: https://mmf-fe.github.io/vue-svgicon/v3/

Download: https://github.com/MMF-FE/vue-svgicon/archive/master.zip

8. vue-material-design-icons

This library is a collection of Vue single-file components to render Material Design Icons, sourced from the MaterialDesign project. It also includes some CSS that helps make the scaling of the icons a little easier.

Demo: https://gitlab.com/robcresswell/vue-material-design-icons

Download: https://gitlab.com/robcresswell/vue-material-design-icons/tree/master

9. vue-ionicons

Vue Icon Set Components from Ionic Team

Design Icons, sourced from the Ionicons project.

Demo: https://mazipan.github.io/vue-ionicons/

Download: https://github.com/mazipan/vue-ionicons/archive/master.zip

10. vue-ico

Dead easy, Google Material Icons for Vue.

This package's aim is to get icons into your Vue.js project as quick as possible, at the cost of all the bells and whistles.

Demo: https://material.io/resources/icons/?style=baseline

Download: https://github.com/paulcollett/vue-ico/archive/master.zip

I hope you like them!

Collection of 10 Vue Markdown Component for Vue.js App in 2020

Collection of 10 Vue Markdown Component for Vue.js App in 2020

Markdown is a way to style text on the web. The 10 Vue markdown components below will give you a clear view.

Markdown is a way to style text on the web. You control the display of the document; formatting words as bold or italic, adding images, and creating lists are just a few of the things we can do with Markdown.

The 10 Vue markdown components below will give you a clear view.

1. Vue Showdown

Use showdown as a Vue component.

View Demo

Download Source

2. showdown-markdown-editor

A markdown editor using codemirror and previewer using showdown for Vue.js.

View Demo

Download Source

3. markdown-it-vue

The vue lib for markdown-it.

View Demo

Download Source

4. perfect-markdown

perfect-markdown is a markdown editor based on Vue & markdown-it. The core is inspired by the implementation of mavonEditor, so perfect-markdown has almost all of the functions of mavonEditor. What's more, perfect-markdown also extends some features based on mavonEditor.

View Demo

Download Source

5. v-markdown-editor

Vue.js Markdown Editor component.

View Demo

Download Source

6. markdown-to-vue-loader

Markdown to Vue component loader for Webpack.

View Demo

Download Source

7. fo-markdown-note Component for Vue.js

fo-markdown-note is a Vue.js component that provides a simple Markdown editor that can be included in your Vue.js project.

fo-markdown-note is a thin Vue.js wrapper around the SimpleMDE Markdown editor JavaScript control.

View Demo

Download Source

8. Vue-SimpleMDE

Markdown Editor component for Vue.js. Support both vue1.0 & vue2.0

View Demo

Download Source

9. mavonEditor

A nice vue.js markdown editor. Support WYSIWYG editing mode, reading mode and so on.

View Demo

Download Source

10. vue-markdown

A Powerful and Highspeed Markdown Parser for Vue.

View Demo

Download Source

Thank for read!

Collection of 15 Vue Input Component for Your Vue.js App

Collection of 15 Vue Input Component for Your Vue.js App

Vue input component gives you a baseline to create your own custom inputs. It consists of a prepend/append slot, messages, and a default slot. In this article I will share 15 Vue input components to you.

Vue input component gives you a baseline to create your own custom inputs. It consists of a prepend/append slot, messages, and a default slot. In this article I will share 15 Vue input components to you.

1. Maska
  • No dependencies
  • Small size (~2 Kb gziped)
  • Ability to define custom tokens
  • Supports repeat symbols and dynamic masks
  • Works on any input (custom or native)

Demo

Download


2. v-range-flyout

A vue component that wraps a input type=number with a customizable range slider flyout with 2-way binding.

Demo

Download


3. vue-tel-input

International Telephone Input with Vue.

Demo

Download


4. Restricted Input

Allow restricted character sets in input elements.

Features

  • Disallow arbitrary characters based on patterns
  • Maintains caret position
  • Format/Update on paste
  • Works in IE11+

Demo

Download


5. Vue Currency Input

The Vue Currency Input plugin allows an easy input of currency formatted numbers.

Demo

Download


6. vue-fields

Input components for vue.js.

Demo

Download


7. vue-material-input

Simple example of issue I am seeing with input labels.

Demo

Download


8. vue-tribute

A Vue.js wrapper for Zurb's Tribute library for native @mentions.

Demo

Download


9. vue-number-smarty

Number input with rich functionality for Vue.js.

Features

  • integer/float
  • signed/unsigned
  • step size
  • increment/decrement value by scrolling when focused
  • align variants
  • min and max boundaries
  • max length of integer part (only for float type)
  • max length of float part (only for float type)
  • max length of string
  • error state
  • readonly state
  • theme options

Demo

Download


10. Vue input mask

Super tiny input mask library for vue.js based on PureMask.js (~2kb) exposed as directive. No dependencies.

Demo

Download


11. vue-r-mask

mask directive for vue.js

  • Template similar to javascript regular expression. /\d{2}/
  • Directive useful for your own input or textarea.
  • Arbitrary number of digits in template /\d{1,10}/

Demo

Download


12. Vue IP

An ip address input with port and material design support.

Demo

Download


13. v-money Mask for Vue.js

Tiny input/directive mask for currency

Features

  • Lightweight (<2KB gzipped)
  • Dependency free
  • Mobile support
  • Component or Directive flavors
  • Accept copy/paste
  • Editable

Demo

Download


14. Vue Masked Input

Dead simple masked input component for Vue.js 2.X. Based on inputmask-core.

Demo

Download


15. VueJS input component

Mobile & Desktop friendly VueJS input component
Features used
CSS variables
Vue's transition-group
Flexbox

Demo


I hope you like them!