Vue.use源码学习小结

2020-06-12 21:11:12易采站长站整理

由于最近在做一些前端的项目,并且接手了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);