博客
关于我
Vue 使用Use、prototype自定义全局插件
阅读量:442 次
发布时间:2019-03-06

本文共 1815 字,大约阅读时间需要 6 分钟。

Vue 使用Useprototype自定义全局插件

 

by:授客 QQ1033553122

 

开发环境

 

Win 10

 

node-v10.15.3-x64.msi

下载地址:

 

实现方式1

1.   src目录下新建plugin目录

2.   plugin目录下新建sendReuest.js

export function sendRequest() {

    console.log("send request by sendRequet Plugin")

}

 

3.   plugin目录下新建customPlugin.js

import * as customPlugin from"./sendRequest"

 

export default customPlugin

 

 

 

4.   plugin目录下新建index.js

// 导入所有接口

import customPlugin from"./customPlugin"

 

const install = Vue=> {

if (install.installed) return// 如果已经注册过了,就跳过

 

install.installed = true

 

Object.defineProperties(Vue.prototype, {

   // 注意,此处挂载在 Vue 原型的 $customPlugin对象上

    $customPlugin: {

       get() {

           return customPlugin

       }

    }

  })

}

 

export default install

 

关于Object.defineProperty

这个函数接受三个参数,一个参数是obj,表示要定义属性的对象,一个参数是prop,是要定义或者更改的属性名字,另外是descriptor,描述符,来定义属性的具体描述。

Object.defineProperty(obj, prop, descriptor)

 

5.   修改main.js

如下,新增带背景色部分的内容

// The Vue build version to load with the `import` command

// (runtime-only or standalone) has been set in webpack.base.conf with an alias.

import Vue from "vue"

import App from "./App"

import router from "./router"

 

 

import customPlugin from "@/plugin/index"

//等价导入方式

// import customPlugin from "@/plugin/"

// import customPlugin from "@/plugin "

 

 

Vue.use(customPlugin)

 

Vue.config.productionTip = false

 

/* eslint-disable no-new */

new Vue({

   el:"#app",

   router,

   components: { App },

   template:"<App/>"

})

 

 

6.   .vue组件中引用

.vue组件使用对应的插件调用sendReuqest方法

methods: {

    sendRequest() {

        this.$customPlugin.sendRequest();

    }

},

 

注意:也可以在某些js中直接引入customPlugin,customPlugin.sendRequest()的方式使用,笔者某次实践时这么使用:pluginName.fileModuleName.functionName(),发现会报错,提示fileModuleNameundefined,解决方法:采用Vue.prototype.$pluginName.fileModuleName.functionName()进行调用。

实现方式2

类似实现方式1,不同的地方在于:

1、去掉第4步

2、第5步,在main.js中添加的内容变成如下

 

import customPlugin from "@/plugin/customPlugin"

 

...略

 

Vue.prototype.$customPlugin = customPlugin

 

参考链接

 

 

转载地址:http://smvfz.baihongyu.com/

你可能感兴趣的文章
机器学习实战 - 读书笔记(14) - 利用SVD简化数据
查看>>
神经网络学习笔记-01-基本概念
查看>>
强化学*读*笔* - 06~07 - 时序差分学*(Temporal-Difference Learning)
查看>>
CSS躬行记(2)——伪类和伪元素
查看>>
编译基础理论
查看>>
数据结构和算法躬行记(2)——栈、队列、散列表和位运算
查看>>
JavaScript作用域原理(一)——作用域链
查看>>
JavaScript作用域原理(三)——作用域根据函数划分
查看>>
JavaScript闭包(一)——实现
查看>>
ios多线程-GCD基本用法
查看>>
最近一个项目的反思
查看>>
grape动态PHP结构(二)——管理后台
查看>>
JavaScript中事件处理
查看>>
前端自动化构建工具gulp记录
查看>>
移动端图片操作(一)——上传
查看>>
Hammer.js分析(四)——recognizer.js
查看>>
移动端 H5图片裁剪插件,内置简单手势操作
查看>>
JavaScript性能优化 DOM编程
查看>>
linux系统常用命令
查看>>
综合架构的简述
查看>>