網站首頁 Vue 正文
一、編寫插件
Vue項目能夠使用很多插件來豐富自己的功能,例如Vue-Router
、Vuex……,這么多插件供我們使用,節省了我們大量的人力和物力,那這些插件是開發出來的呢?是不是我們自己也想擁有一個屬于自己的vue插件,下面就展示一下如何寫一個自己的Vue插件。
1.1 包含install()方法的Object
Vue插件可以是一個包含install
方法的Object
對象,此時插件被調用時會調用install方法,
如下所示:
export default { // 接收兩個參數 // app: 應用上下文的實例 // options:插件輸入的選項 install: (app, options) => { console.log('app', app); console.log('options', options); // 做一些處理 // …… } }
1.2 通過function的方式
Vue插件也可以是一個function
函數,此時插件被調用時會調用function
函數本身,
如下所示:
export default function TestPlugin(app, options) { console.log('app', app); console.log('options', options); }
二、使用插件
上述已經闡述了如何編寫自己的插件,插件編寫完了之后就需要使用這些插件了,那這些插件應該如何使用呢?其實用起來很簡單,應用上下文的實例上提供了對應的use方法。
app.use(plugin, [options]); // 返回一個應用實例,所以其可以鏈式添加新的插件
三、app.use()是如何執行插件的
為什么app.use()
可以使用這些插件呢?本著“知其然而知其所以然”的精神,一起來扒一扒為什么。如下是對應的源碼:
function createApp(rootComponent, rootProps = null) { // …… const installedPlugins = new Set(); const app = (context.app = { // …… use(plugin, ...options) { if (installedPlugins.has(plugin)) { warn(`Plugin has already been applied to target app.`); } else if (plugin && shared.isFunction(plugin.install)) { installedPlugins.add(plugin); plugin.install(app, ...options); } else if (shared.isFunction(plugin)) { installedPlugins.add(plugin); plugin(app, ...options); } else { warn(`A plugin must either be a function or an object with an "install" ` + `function.`); } return app; }, // …… }); return app; };
上述代碼讀起來很簡單,其實現了以下幾件事情:
- 利用
Set
結構存儲插件,當存在該插件時拋出異常; - 通過判斷是否存在
install
方法或是否是函數,執行對應的插件; - 執行插件時將
app
上下文實例和options
作為參數傳入;
原文鏈接:https://developer.51cto.com/article/700581.html
相關推薦
- 2022-07-24 Python實現FIFO緩存置換算法_python
- 2022-03-31 C#實現單位換算器_C#教程
- 2022-10-14 VSC下編寫Makefile文件時,在終端運行make clean命令時報錯的解決方法
- 2022-01-25 win10 更換JDK后 查詢JDK路徑還是原路徑怎么辦?
- 2022-04-14 Python函數式編程實現登錄注冊功能_python
- 2022-05-21 淺談GO中的Channel以及死鎖的造成_Golang
- 2022-06-11 ASP.NET登出系統并清除Cookie_實用技巧
- 2022-06-29 Oracle中PL/SQL的塊與表達式_oracle
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支