Table of Contents
Understanding plug-ins
Develop vue-toast
Home Web Front-end JS Tutorial Detailed explanation of Vue.js plug-in development

Detailed explanation of Vue.js plug-in development

Apr 05, 2017 pm 01:43 PM

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 上实现
    // 逻辑...
  }
}
Copy after login

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;
Copy after login

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);
Copy after login

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
    }
}
Copy after login

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: &#39;<p class="vue-toast">&#39; + tips + &#39;</p>&#39;
        });
        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;
Copy after login

It seems very simple, we implemented this.$toast(), and then display different positions.

<p style="margin-bottom: 7px;">// toast.js<br/>[&#39;bottom&#39;, &#39;center&#39;, &#39;top&#39;].forEach(type => {<br/>    Vue.prototype.$toast[type] = (tips) => {<br/>        return Vue.prototype.$toast(tips,type)<br/>    }<br/>})<br/></p>
Copy after login

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: &#39;<p class="vue-toast toast-&#39;+ type +&#39;">&#39; + tips + &#39;</p>&#39;
    });
    ...
}
Copy after login

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:&#39;bottom&#39;,   // 默认显示位置
        duration:&#39;2500&#39;         // 持续时间
    }
    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(&#39;vue-toast&#39;).length){
            // 如果toast还在,则不再执行
            return;
        }
        let toastTpl = Vue.extend({
            template: &#39;<p class="vue-toast toast-&#39;+opt.defaultType+&#39;">&#39; + tips + &#39;</p>&#39;
        });
        let tpl = new toastTpl().$mount().$el;
        document.body.appendChild(tpl);
        setTimeout(function () {
            document.body.removeChild(tpl);
        }, opt.duration)
    }
    [&#39;bottom&#39;, &#39;center&#39;, &#39;top&#39;].forEach(type => {
        Vue.prototype.$toast[type] = (tips) => {
            return Vue.prototype.$toast(tips,type)
        }
    })
}
module.exports = Toast;
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PyCharm Beginner's Guide: Comprehensive understanding of plug-in installation! PyCharm Beginner's Guide: Comprehensive understanding of plug-in installation! Feb 25, 2024 pm 11:57 PM

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] Error loading plugin in Illustrator [Fixed] Feb 19, 2024 pm 12:00 PM

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

Share three solutions to why Edge browser does not support this plug-in Share three solutions to why Edge browser does not support this plug-in Mar 13, 2024 pm 04:34 PM

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.

What is the Chrome plug-in extension installation directory? What is the Chrome plug-in extension installation directory? Mar 08, 2024 am 08:55 AM

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

How to add WeChat mini program functionality to WordPress plug-in How to add WeChat mini program functionality to WordPress plug-in Sep 06, 2023 am 09:03 AM

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

Does PyCharm Community Edition support enough plugins? Does PyCharm Community Edition support enough plugins? Feb 20, 2024 pm 04:42 PM

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

Detailed explanation of how to install and set up the EclipseSVN plug-in Detailed explanation of how to install and set up the EclipseSVN plug-in Jan 28, 2024 am 08:42 AM

Detailed explanation of how to install and set up the EclipseSVN plug-in Eclipse is a widely used integrated development environment (IDE) that supports many different plug-ins to extend its functionality. One of them is the EclipseSVN plugin, which enables developers to interact with the Subversion version control system. This article will detail how to install and set up the EclipseSVN plug-in and provide specific code examples. Step 1: Install the EclipseSVN plug-in and open Eclipse

PyCharm plug-in installation tips are shared to help you get twice the result with half the effort! PyCharm plug-in installation tips are shared to help you get twice the result with half the effort! Feb 21, 2024 pm 06:36 PM

PyCharm is a powerful Python integrated development environment. By installing plug-ins, you can further improve development efficiency and facilitate developers' work. This article will share some tips on PyCharm plug-in installation, so that you can get twice the result with half the effort, while also providing specific code examples to demonstrate how to use the plug-in. Step 1: Open PyCharm, click "File" in the menu bar, and then select "Settings". Step 2: In the Settings window, click "

See all articles