写给小白的 Vue 插件篇

简介: 如何开发 Vue 插件

## 目的

“插件通常用来为 Vue 添加全局功能。”  

“组件是可复用的 Vue 实例,且带有一个名字。”  

—— Vue.js 官网


官网插件例子做的比较粗糙,不能顺畅的理解插件,故自己试试




## 实操


`1、先写插件内容(类似组件)`



```

<!-- src/components/Warning/index.vue -->

<template>

 <transition name="fade">

   <p v-show="isShow" class="msg">{{ msg }}</p>

 </transition>

</template>


<script>

export default {

 data() {

   return {

     msg: 'warning',

     isShow: false,

     duration: 1,

   }

 },

 mounted() {

   this.isShow = true

   setTimeout(() => {

     this.isShow = false

   }, this.duration * 1000)

 },

}

</script>


<style>

.msg {

 display: flex;

 justify-content: center;

 align-items: center;

}

</style>


```



`2、手动挂载 warning 的 dom`


```

// src/components/Warning/index.js

import Vue from 'vue'

import Warning from './index.vue'


const WarningConstructor = Vue.extend(Warning) // 生成构造器


const warning = function(options={}) {

   const warningChild = new WarningConstructor({ // 实例

       data:options

   }).$mount() // 挂载


   const realDom = warningChild.$el // 真实 dom

   document.body.appendChild(realDom)


   return warningChild

}


export default warning

```

`3、暴露 install 方法 传入 Vue.use()`


```

// src/components/index.js

import waring from './Toast/index';


// Vue.js 的插件应该暴露一个 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象

const install = function (Vue) {

 if (install.installed) return;

 install.installed = true;


 // 将包装好的 warning 挂到Vue的原型上,作为 Vue 实例上的方法

 Vue.prototype.$waring = waring;

}


export default {

 install,

};

```


4、使用


```

// main.js

import waring from '../src/components/index.js';

Vue.use(waring);

```



```

// App.vue

<template>

   <button @click="handleClick">点击弹出文字</button>

</template>


methods: {

   handleClick() {

     this.$waring()

   },

 },

```


## 效果展示



![Kapture 2023-03-08 at 15.00.54.gif](https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/dce9b9e8ff764496a5e41e832c47d867~tplv-k3u1fbpfcp-watermark.image?)




* good 下节见!



相关文章
|
存储 缓存 资源调度
项目中的yarn.lock文件的作用
项目中的yarn.lock文件的作用
1564 0
项目中的yarn.lock文件的作用
|
域名解析 负载均衡 网络协议
DNS 的应用场景|学习笔记
快速学习DNS 的应用场景
DNS 的应用场景|学习笔记
|
安全 Android开发 数据安全/隐私保护
|
存储 人工智能 算法
Unity 实现A* 寻路算法
Unity 实现A* 寻路算法
1089 2
Unity 实现A* 寻路算法
|
机器学习/深度学习 缓存 并行计算
PICASSO,一个高效的搜推广稀疏训练解决方案
近日,阿里巴巴自研稀疏训练引擎论文《PICASSO: Unleashing the Potential of GPU-centric Training for Wide-and-deep Recommender Systems》被国际数据工程顶级会议ICDE 2022 (International Conference on Data Engineering)收录。文中介绍了名为PICASSO(Packing, Interleaving and Caching Augmented Software System Optimization)的训练引擎所使用的核心技术。
|
数据可视化 Shell 持续交付
|
Java 开发工具
Lombok 同时使用 @Data 和 @Builder 的巨坑,千万别乱用!(1)
Lombok 同时使用 @Data 和 @Builder 的巨坑,千万别乱用!
1216 0
Lombok 同时使用 @Data 和 @Builder 的巨坑,千万别乱用!(1)
|
存储 编译器 C语言
C++多态性原理详解(静态多态、动态多态、虚函数、虚函数表)
C++多态性原理详解(静态多态、动态多态、虚函数、虚函数表)
1208 0
C++多态性原理详解(静态多态、动态多态、虚函数、虚函数表)
|
IDE 搜索推荐 Java
(2021 最新版)IntelliJ IDEA 下载安装及配置教程
(2021 最新版)IntelliJ IDEA 下载安装及配置教程
1891 0
(2021 最新版)IntelliJ IDEA 下载安装及配置教程

热门文章

最新文章