国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Vue.use源碼學習小結

2024-05-06 15:33:15
字體:
來源:轉載
供稿:網友

由于最近在做一些前端的項目,并且接手了Weex的項目,所以難免和Vue打起了交道,js也是從入門到學習中。項目里用到了Vue的插件機制,所以看了看Vue.use的源碼,還是比較簡單的,適合新手閱讀,所以記錄下來以免遺忘。

感謝

本文最后一章節[結合實際場景]是參考了eros 這個開源項目的,感謝eros項目組的開發。

什么是Vue插件

關于什么是Vue插件大家可以去看官網的解釋 ,總得來說就是提供一個全局注冊/調用的能力。

怎么用

我們以Weex為例。

首先有一個toast.js

const Toast = {}Toast.install = (Vue, options) => {  Vue.prototype.$toast = (msg, duration = 0.8) => {    const modal = weex.requireModule('modal')    modal.toast({      message: msg,      duration: 0.8    })  }}Vue.use(Toast)

很簡單,就是定義了一個Toast對面,然后給Toast對象創建一個install方法,方法里給Vue的prototype創建了一個$toast方法,該方法就是調用modal去彈一個toast,最后使用Vue.use方法去注冊這個Toast插件。

然后我們還有一個index.vue:

<template> <div> <div class="box" @click="onclick" @longpress="onlongpress" @appear="onappear" @disappear="ondisappear"></div>  </div></template><script> const modal = weex.requireModule('modal') export default {   methods: {     onclick (event) {       this.$toast("aaa", 0.8)     },     onlongpress (event) {       console.log('onlongpress:', event)       modal.toast({         message: 'onlongpress',         duration: 0.8       })     },     onappear (event) {       console.log('onappear:', event)       modal.toast({         message: 'onappear',          duration: 0.8        })      },      ondisappear (event) {        console.log('ondisappear:', event)        modal.toast({          message: 'ondisappear',          duration: 0.8        })      }   } }</script><style scoped>.box {  border-width: 2px;  border-style: solid;  border-color: #BBB;  width: 250px;  height: 250px;  margin-top: 250px;  margin-left: 250px;  background-color: #EEE;}</style>

在其中調用了this.$toast去使用插件的方法。

由此我們可以知道,Vue的插件機制就是通過Vue.use方法去注冊的。

源碼分析

Vue.use = function (plugin) {  if (plugin.installed) {    return  }  var args = toArray(arguments, 1);  args.unshift(this);  if (typeof plugin.install === 'function') {    plugin.install.apply(plugin, args);  } else if (typeof plugin === 'function') {    plugin.apply(null, args);  }  plugin.installed = true;  return this};function toArray (list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) {  ret[i] = list[i + start]; } return ret}            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 曲麻莱县| 宁城县| 崇信县| 遂宁市| 洛浦县| 民乐县| 施甸县| 伊川县| 玉树县| 界首市| 鸡西市| 巴楚县| 开阳县| 喜德县| 皮山县| 福建省| 和平区| 新龙县| 双桥区| 安泽县| 宝兴县| 高青县| 永寿县| 桐乡市| 岗巴县| 灵宝市| 钟山县| 凤庆县| 宝鸡市| 新营市| 喀喇沁旗| 清镇市| 溆浦县| 靖江市| 山西省| 合作市| 府谷县| 广灵县| 南陵县| 建湖县| 建湖县|