实现一个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/

Logo

前往低代码交流专区

更多推荐