Vue Plugin Vue插件
实现一个VUE插件const msgPlugin={}msgPlugin.install=function(Vue, options){//全局方法Vue.haha=function(){alert('我是全局')}//实例方法Vue.prototype.myalert=function(){alert('我是插件里面的全局方法')}//混入Vue.mixin({.
·
实现一个VUE插件
const msgPlugin={}
msgPlugin.install=function(Vue, options){
//全局方法
Vue.haha=function(){
alert('我是全局')
}
//实例方法
Vue.prototype.myalert=function(){
alert('我是插件里面的全局方法')
}
//混入
Vue.mixin({
created:function(){
console.log('create')
}
})
Vue.directive('xiaobu', {
// 当被绑定的元素插入到 DOM 中时……
inserted: function (el,binding) {
el.setAttribute(
"id",
new Date().getTime()
);
if(binding.arg){
console.log('arg='+ binding.arg)
}
}
})
}
export default msgPlugin
全局配置引用
Vue.use(msgPlugin)
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
具体页面组件中使用
<template>
<div class="about" v-xiaobu>
<div v-xiaobu:aaaaaa="123">
<h1 >This is an about page</h1>
</div>
</div>
</template>
<script>
import Vue from 'vue'
export default {
name: 'About',
components: {
},
mounted(){
this.myalert()
Vue.haha()
}
}
</script>
提问:Vue.use做了什么?
看下面源码,关键的一句:plugin.install.apply(plugin, args) ,其实就是调用了install方法
import { toArray } from '../util/index'
export function initUse (Vue: GlobalAPI) {
Vue.use = function (plugin: Function | Object) {
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// additional parameters
const 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)
}
installedPlugins.push(plugin)
return this
}
}
Vue.use 参见:https://blog.csdn.net/ZYS10000/article/details/107246076/
更多推荐
已为社区贡献4条内容
所有评论(0)