我是靠谱客的博主 震动微笑,这篇文章主要介绍Vue-插件开发,现在分享给大家,希望可以做个参考。

插件分类

preview

Vue.js 的插件应当有一个公开方法 install 。这个方法的第一个参数是 Vue 构造器 , 第二个参数是一个可选的选项对象:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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 上实现 // 逻辑... } }


loading插件写法

目录结构:


1.loading组件

nwd-loading.vue:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
<template> <div class="nwd-loading" v-show="show"> <div>{{text}}</div> </div> </template> <script> export default { props: { show: Boolean, text: "正在加载中..." } } </script>

2.封装插件

index.js

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import NwdLoadingComponent from './nwd-loading' let $vm; export default { install(Vue,options) { if(!$vm) { const NwdLoadingPlugin = Vue.extend(NwdLoadingComponent); $vm = new NwdLoadingPlugin({ el: document.createElement('div') }); } $vm.show = false; let loading = { show(text) { $vm.show = true; $vm.text = text; document.body.appendChild($vm.$el); }, hide() { $vm.show = false; } }; if (!Vue.$loading) { Vue.$loading = loading; } // Vue.prototype.$loading = Vue.$loading; Vue.mixin({ created() { this.$loading = Vue.$loading; } }) } }

注释:通过Vue.extend()方法创建了一个构造器NwdLoadingPlugin,其次我们再通过new NwdLoadingPlugin()  创建了实例$vm,并挂载到一个div元素上。最后我们需要通过document.body.appendChild($vm.$el)将其插入到DOM节点中。

当我们创建了$vm实例后,我们可以访问该实例的属性和方法,比如通过$vm.show就可以改变NwdLoadingComponent组件的show值来控制其显示隐藏。

最终我们通过Vue.mixin或者Vue.prototype.$loading来全局添加了$loading事件,其又包含了show和hide两个方法。我们可以直接在页面中使用this.$loading.show()来显示加载,使用this.$loading.hide()来关闭加载。

3.使用插件

main.js

复制代码
1
2
3
import NwdLoading from '@/components/nwd-loading/index.js' Vue.use(NwdLoading)

4. 调用插件

....vue

复制代码
1
2
3
4
5
6
export default { created() { this.$loading.show("loading内容") } }


最后

以上就是震动微笑最近收集整理的关于Vue-插件开发的全部内容,更多相关Vue-插件开发内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(65)

评论列表共有 0 条评论

立即
投稿
返回
顶部