Detailed explanation of Vue.js plug-in development
Preface
As Vue.js becomes more and more popular, Vue.js related plug-ins are constantly being contributed, countless. For example, the officially recommended vue-router, vuex, etc. are all very excellent plug-ins. But more of us are still at the stage of using it and rarely develop it ourselves. So next, we will learn about the development and use of the plug-in through a simple vue-toast plug-in.
Understanding plug-ins
If you want to develop a plug-in, you must first know what a plug-in looks like.
Vue.js plug-ins should have a public method install. The first parameter of this method is the Vue constructor, and the second parameter is an optional options object:
MyPlugin.install = function (Vue, options) { Vue.myGlobalMethod = function () { // 1. 添加全局方法或属性,如: vue-custom-element // 逻辑... } Vue.directive('my-directive', { // 2. 添加全局资源:指令/过滤器/过渡等,如 vue-touch bind (el, binding, vnode, oldVnode) { // 逻辑... } ... }) Vue.mixin({ created: function () { // 3. 通过全局 mixin方法添加一些组件选项,如: vuex // 逻辑... } ... }) Vue.prototype.$myMethod = function (options) { // 4. 添加实例方法,通过把它们添加到 Vue.prototype 上实现 // 逻辑... } }
The vue-toast plug-in to be talked about next is implemented by adding instance methods. Let's look at a small example first. First create a new js file to write the plug-in: toast.js
// toast.js var Toast = {}; Toast.install = function (Vue, options) { Vue.prototype.$msg = 'Hello World'; } module.exports = Toast;
In main.js, you need to import toast.js and use the plug-in through the global method Vue.use():
// main.js import Vue from 'vue'; import Toast from './toast.js'; Vue.use(Toast);
Then, we get the $msg attribute defined by the plug-in in the component.
// App.vue export default { mounted(){ console.log(this.$msg); // Hello World } }
As you can see, the console successfully printed Hello World. Now that $msg can be obtained, we can implement our vue-toast plug-in.
Develop vue-toast
Requirements: Call this.$toast('Network request failed') in the component to pop up a prompt, which is displayed at the bottom by default. You can display it in different positions by calling methods such as this.$toast.top() or this.$toast.center().
To sort out my thoughts, when a prompt pops up, I can add a p in the body to display the prompt information. I can locate different positions by adding different class names, and then I can start writing.
// toast.js var Toast = {}; Toast.install = function (Vue, options) { Vue.prototype.$toast = (tips) => { let toastTpl = Vue.extend({ // 1、创建构造器,定义好提示信息的模板 template: '<p class="vue-toast">' + tips + '</p>' }); let tpl = new toastTpl().$mount().$el; // 2、创建实例,挂载到文档以后的地方 document.body.appendChild(tpl); // 3、把创建的实例添加到body中 setTimeout(function () { // 4、延迟2.5秒后移除该提示 document.body.removeChild(tpl); }, 2500) } } module.exports = Toast;
It seems very simple, we implemented this.$toast(), and then display different positions.
<p style="margin-bottom: 7px;">// toast.js<br/>['bottom', 'center', 'top'].forEach(type => {<br/> Vue.prototype.$toast[type] = (tips) => {<br/> return Vue.prototype.$toast(tips,type)<br/> }<br/>})<br/></p>
Here the type is passed to $toast and processed at different positions in this method. As mentioned above, it is achieved by adding different class names (toast-bottom, toast-top, toast-center), then The $toast method needs a slight modification.
Vue.prototype.$toast = (tips,type) => { // 添加 type 参数 let toastTpl = Vue.extend({ // 模板添加位置类 template: '<p class="vue-toast toast-'+ type +'">' + tips + '</p>' }); ... }
It seems almost done. But if I want to display it at the top by default, it seems a bit redundant that I have to call this.$toast.top() every time. Can I just put this.$toast() directly where I want it? And I don’t want it to disappear after 2.5 seconds? At this time, we noticed the options parameter in Toast.install(Vue,options). We can pass in the parameters we want through options in Vue.use(). The final modification of the plug-in is as follows:
var Toast = {}; Toast.install = function (Vue, options) { let opt = { defaultType:'bottom', // 默认显示位置 duration:'2500' // 持续时间 } for(let property in options){ opt[property] = options[property]; // 使用 options 的配置 } Vue.prototype.$toast = (tips,type) => { if(type){ opt.defaultType = type; // 如果有传type,位置则设为该type } if(document.getElementsByClassName('vue-toast').length){ // 如果toast还在,则不再执行 return; } let toastTpl = Vue.extend({ template: '<p class="vue-toast toast-'+opt.defaultType+'">' + tips + '</p>' }); let tpl = new toastTpl().$mount().$el; document.body.appendChild(tpl); setTimeout(function () { document.body.removeChild(tpl); }, opt.duration) } ['bottom', 'center', 'top'].forEach(type => { Vue.prototype.$toast[type] = (tips) => { return Vue.prototype.$toast(tips,type) } }) } module.exports = Toast;
In this way, a simple vue plug-in is implemented, and can be packaged and released through npm. You can use npm install to install it next time
The above is the detailed content of Detailed explanation of Vue.js plug-in development. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PyCharm is a powerful and popular Python integrated development environment (IDE) that provides a wealth of functions and tools so that developers can write code more efficiently. The plug-in mechanism of PyCharm is a powerful tool for extending its functions. By installing different plug-ins, various functions and customized features can be added to PyCharm. Therefore, it is crucial for newbies to PyCharm to understand and be proficient in installing plug-ins. This article will give you a detailed introduction to the complete installation of PyCharm plug-in.
![Error loading plugin in Illustrator [Fixed]](https://img.php.cn/upload/article/000/465/014/170831522770626.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
When launching Adobe Illustrator, does a message about an error loading the plug-in pop up? Some Illustrator users have encountered this error when opening the application. The message is followed by a list of problematic plugins. This error message indicates that there is a problem with the installed plug-in, but it may also be caused by other reasons such as a damaged Visual C++ DLL file or a damaged preference file. If you encounter this error, we will guide you in this article to fix the problem, so continue reading below. Error loading plug-in in Illustrator If you receive an "Error loading plug-in" error message when trying to launch Adobe Illustrator, you can use the following: As an administrator

What is the Chrome plug-in extension installation directory? Under normal circumstances, the default installation directory of Chrome plug-in extensions is as follows: 1. The default installation directory location of chrome plug-ins in windowsxp: C:\DocumentsandSettings\username\LocalSettings\ApplicationData\Google\Chrome\UserData\Default\Extensions2. chrome in windows7 The default installation directory location of the plug-in: C:\Users\username\AppData\Local\Google\Chrome\User

When users use the Edge browser, they may add some plug-ins to meet more of their needs. But when adding a plug-in, it shows that this plug-in is not supported. How to solve this problem? Today, the editor will share with you three solutions. Come and try it. Method 1: Try using another browser. Method 2: The Flash Player on the browser may be out of date or missing, causing the plug-in to be unsupported. You can download the latest version from the official website. Method 3: Press the "Ctrl+Shift+Delete" keys at the same time. Click "Clear Data" and reopen the browser.

How to use WordPress plug-ins to achieve instant location functionality With the popularity of mobile devices, more and more websites are beginning to provide geolocation-based services. In WordPress websites, we can use plug-ins to implement instant positioning functions and provide visitors with services related to their geographical location. 1. Choose the right plug-in. There are many plug-ins that provide geolocation services in the WordPress plug-in library to choose from. Depending on the needs and requirements, choosing the right plug-in is the key to achieving instant positioning functionality. Here are a few

Does PyCharm Community Edition support enough plugins? Need specific code examples As the Python language becomes more and more widely used in the field of software development, PyCharm, as a professional Python integrated development environment (IDE), is favored by developers. PyCharm is divided into two versions: professional version and community version. The community version is provided for free, but its plug-in support is limited compared to the professional version. So the question is, does PyCharm Community Edition support enough plug-ins? This article will use specific code examples to

How to Add WeChat Mini Program Functions to WordPress Plugins With the popularity and popularity of WeChat mini programs, more and more websites and applications are beginning to consider integrating them with WeChat mini programs. For websites that use WordPress as their content management system, adding the WeChat applet function can provide users with a more convenient access experience and more functional choices. This article will introduce how to add WeChat mini program functionality to WordPress plug-in. Step 1: Register a WeChat mini program account. First, you need to open the WeChat app

How to Add Online Ordering Function to WordPress Plugin In today’s digital era, many restaurants and coffee shops have chosen to move the ordering process online to meet the needs of customers. WordPress is a widely used content management system (CMS), and many businesses are using WordPress to build their websites. This article will introduce how to add online ordering functionality to WordPress plug-in and provide corresponding code examples. Step 1: Choose the Right Plugin First, we need to create a custom plugin in WordPress
