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


Vue 使用Useprototype自定義全局插件

 

by:授客 QQ1033553122

 

開發環境

 

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(),發現會報錯,提示fileModuleNameundefined,解決方法:采用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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM