前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Vue 使用Use、prototype自定义全局插件

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

作者头像
授客
发布2020-06-02 16:01:05
9160
发布2020-06-02 16:01:05
举报
文章被收录于专栏:授客的专栏授客的专栏

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

by:授客

开发环境

Win 10

node-v10.15.3-x64.msi

下载地址:

https://nodejs.org/en/

实现方式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(),发现会报错,提示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://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-05-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 开发环境
  • 实现方式1
    • 1. src目录下新建plugin目录
      • 2. plugin目录下新建sendReuest.js
        • 3. plugin目录下新建customPlugin.js
          • 4. plugin目录下新建index.js
            • 5. 修改main.js
              • 6. .vue组件中引用
              • 实现方式2
              • 参考链接
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档