Home Web Front-end JS Tutorial How to write vue plug-in vue.js example tutorial

How to write vue plug-in vue.js example tutorial

Dec 12, 2017 pm 03:09 PM
javascript vue.js plug-in

This article mainly shares with you how to write vue plug-ins. Before learning, ask yourself why you should write vue plug-ins.

In a project, especially a large project, there are many parts that need to be reused, such as loading animations and pop-up boxes. It is a little troublesome to reference one by one, and if there are too many components referenced in a vue file, the code will appear bloated, so there is a need to encapsulate the vue plug-in.

After talking about the requirements, let’s take a look at the specific implementation. At present, I have tried two different plug-in writing methods, and I will introduce them one by one.

This is my project directory. The general structure is explained like this, as simple as possible and easy to understand.

One is the loading plug-in and the other is the toast plug-in. The difference is that the loading plug-in is introduced as a component, while the toast plug-in is directly added to the mount point and called by changing the status of the method.

Currently used is Jiangzi:

toast plug-in

There are two files under the toast file, the file with the suffix vue is The skeleton of this plug-in, the first js file is to put this skeleton into the Vue global and write the operation logic.

You can take a look at the content of toast.vue:


<template>
 <transition name="fade">
  <p v-show="show">
   {{message}}
  </p>

 </transition>
</template>

<script>
export default {
 data() {
 return {
  show: false,
  message: ""
 };
 }
};
</script>

<style lang="scss" scoped>
.toast {
 position: fixed;
 top: 40%;
 left: 50%;
 margin-left: -15vw;
 padding: 2vw;
 width: 30vw;
 font-size: 4vw;
 color: #fff;
 text-align: center;
 background-color: rgba(0, 0, 0, 0.8);
 border-radius: 5vw;
 z-index: 999;
}

.fade-enter-active,
.fade-leave-active {
 transition: 0.3s ease-out;
}
.fade-enter {
 opacity: 0;
 transform: scale(1.2);
}
.fade-leave-to {
 opacity: 0;
 transform: scale(0.8);
}
</style>
Copy after login


The main thing here There are only two contents, show that determines whether to display and message that determines what content to display.

After a quick look here, do you find any problems?

There is no props attribute in this file, that is, whether it is show or message, there is no way to modify it through parent-child component communication. So how do they handle it correctly? Of. Don't worry, let's take a look at his configuration file.

index.js:


import ToastComponent from &#39;./toast.vue&#39;

const Toast = {};

// 注册Toast
Toast.install = function (Vue) {
 // 生成一个Vue的子类
 // 同时这个子类也就是组件
 const ToastConstructor = Vue.extend(ToastComponent)
 // 生成一个该子类的实例
 const instance = new ToastConstructor();

 // 将这个实例挂载在我创建的p上
 // 并将此p加入全局挂载点内部
 instance.$mount(document.createElement(&#39;p&#39;))
 document.body.appendChild(instance.$el)
 
 // 通过Vue的原型注册一个方法
 // 让所有实例共享这个方法 
 Vue.prototype.$toast = (msg, duration = 2000) => {
  instance.message = msg;
  instance.show = true;

  setTimeout(() => {
   
   instance.show = false;
  }, duration);
 }
}

export default Toast
Copy after login


##The logic here can be roughly divided into several steps. :

Create an empty object. This object is the name of the plug-in to be used in the future. In addition, there must be an install function in this object. Use vue's extend method to create a plug-in constructor (which can be seen as creating a subclass of vue), instantiate the subclass, and all subsequent operations can be completed through this subclass. Then add a shared method to the Vue prototype.

What needs to be mentioned here is

Vue.extend(). For example, our daily use of vue to write components looks like this:


Vue.component(&#39;MyComponent&#39;,{
 template:&#39;<p>这是组件</p>&#39;
})
Copy after login


This is a global component Registration method, but in fact this is syntax sugar, the real running process is like this:


let component = Vue.extend({
 template:&#39;<p>这是组件</p>&#39;
})

Vue.component(&#39;MyComponent&#39;,component)
Copy after login


Vue.extend will return an object. According to most information, it can also be said to return a subclass of Vue. Since it is a subclass, there is no way to directly use the methods on the Vue prototype through it, so new is needed. An example comes out for use.

In the code console.log(instance)


the result is this:

You can see $el:p.toast

is the root node of the toast component template.

What’s confusing is that I don’t know why I need to create an empty p node and mount this instance on it. I tried commenting this code, but when I run it I get an error.

Looking for the cause of this error, it seems to be because


document.body.appendChild(instance.$el)
Copy after login


##There is a problem with

instance.$el

, okay, let’s check this in the console. WTF! ! ! ! The result turned out to be undefined. Then go on

console.log(instance)
Copy after login


And up Comparing a picture, what did you find? Yes, $el disappeared. In other words, after I commented the sentence

instance.$mount(document.createElement(&#39;p&#39;))
Copy after login


, The mount point no longer exists. Then I tried to change this sentence:

instance.$mount(instance.$el)
Copy after login


$el magically came back... …………

No problems have been found with this change for the time being, and it can be run as above. But in any case, this means that the instance must be mounted on a node for subsequent operations. The code after

is simple. It is nothing more than adding a method to change the plug-in state on the Vue prototype. Then export this object.

The next step is how to use it. Let’s take a look at how main.js is written:

import Vue from &#39;vue&#39;
import App from &#39;./App&#39;
// import router from &#39;./router&#39;
import Toast from &#39;./components/taost&#39;
Vue.use(Toast)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({

 // router,
 render: h => h(App)
}).$mount(&#39;#app&#39;)
Copy after login


##This way you can use it in other vue files Use it directly, like this:

// app.vue
<template>
 <p id="app">
 <loading duration=&#39;2s&#39; :isshow=&#39;show&#39;></loading>
 <!-- <button @click="show = !show">显示/隐藏loading</button> -->
 <button @click="toast">显示taost弹出框</button>
 </p>
</template>

<script>
export default {
 name: "app",
 data() {
 return {
  show: false
 };
 },
 methods: {
 toast() {
  this.$toast("你好");
 }
 }
};
</script>

<style>
#app {
 font-family: "Avenir", Helvetica, Arial, sans-serif;
 -webkit-font-smoothing: antialiased;
 -moz-osx-font-smoothing: grayscale;
 text-align: center;
 color: #2c3e50;
 margin-top: 60px;
}
</style>
Copy after login



通过在methods中增加一个方法控制写在Vue原型上的$toast对toast组件进行操作。

这样toast组件的编写过程就结束了,可以看到一开始gif图里的效果。

loading插件

经过上一个插件的讲解,这一部分就不会那么细致了,毕竟大多数都没有什么不同,我只指出不一样的地方。


<template>
 <p class=&#39;wrapper&#39; v-if="isshow">
  <p class=&#39;loading&#39;>
   <img src="./loading.gif">
  </p>
 </p>
</template>

<script>
export default {
 props: {
 duration: {
  type: String,
  default: "1s" //默认1s
 },
 isshow: {
  type: Boolean,
  default: false
 }
 },
 data: function() {
 return {};
 }
};
</script>

<style lang="scss" scoped>

</style>
Copy after login



这个就只是一个模板,传入两个父组件的数据控制显示效果。

那再来看一下该插件的配置文件:


import LoadingComponent from &#39;./loading.vue&#39;

let Loading = {};

Loading.install = (Vue) => {
 Vue.component(&#39;loading&#39;, LoadingComponent)
}

export default Loading;
Copy after login



这个和taoat的插件相比,简单了很多,依然是一个空对象,里面有一个install方法,然后在全局注册了一个组件。

比较

那介绍了这两种不同的插件编写方法,貌似没有什么不一样啊,真的是这样么?

来看一下完整的main.js和app.vue这两个文件:


// main.js
import Vue from 'vue'
import App from './App'
// import router from './router'
import Toast from './components/taost'
import Loading from './components/loading'

Vue.use(Toast)

Vue.use(Loading)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({

 // router,
 render: h => h(App)
}).$mount('#app')

// app.vue
<template>
 <p id="app">
 <loading duration=&#39;2s&#39; :isshow=&#39;show&#39;></loading>
 <!-- <button @click="show = !show">显示/隐藏loading</button> -->
 <button @click="toast">显示taost弹出框</button>
 </p>
</template>

<script>
export default {
 name: "app",
 data() {
 return {
  show: false
 };
 },
 methods: {
 toast() {
  this.$toast("你好");
 }
 }
};
</script>

<style>
#app {
 font-family: "Avenir", Helvetica, Arial, sans-serif;
 -webkit-font-smoothing: antialiased;
 -moz-osx-font-smoothing: grayscale;
 text-align: center;
 color: #2c3e50;
 margin-top: 60px;
}
</style>
Copy after login



可以看出来,loading是显示的写在app.vue模板里的,而toast并没有作为一个组件写入,仅仅是通过一个方法控制显示。

来看一下html结构和vue工具给出的结构:

看出来了么,toast插件没有在挂载点里面,而是独立存在的,也就是说当执行


vue.use(toast)
Copy after login


相关推荐:

vue组件的3种书写形式详解

实用的vue.js项目中小技巧汇总

Vue.js划分组件的实现方法介绍

The above is the detailed content of How to write vue plug-in vue.js example tutorial. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 Beginner's Guide: Comprehensive understanding of plug-in installation!

Error loading plugin in Illustrator [Fixed] Error loading plugin in Illustrator [Fixed] Feb 19, 2024 pm 12:00 PM

Error loading plugin in Illustrator [Fixed]

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?

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

Share three solutions to why Edge browser does not support this plug-in

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?

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 plug-in installation tips are shared to help you get twice the result with half the effort!

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

Simple JavaScript Tutorial: How to Get HTTP Status Code

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

See all articles