html引入prototype插件,Vue 使用Use、prototype自定义全局插件

Vue使用Use、prototype自定义全局插件

by:授客QQ:1033553122

开发环境

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:""

})

6.   .vue组件中引用

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

methods: {

sendRequest() {

this.$customPlugin.sendRequest();

}

},

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

实现方式2

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

1、去掉第4步

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

import customPlugin from "@/plugin/customPlugin"

...略

Vue.prototype.$customPlugin = customPlugin

参考链接

本文来源于网络:查看 >https://www.cnblogs.com/shouke/p/13022462.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值