【Vue】Vue插件-自定义插件库

具体见 官方教程 https://cn.vuejs.org/v2/guide/plugins.html
这里给出一个小demo示例

  • 开发插件的js模板
MyPlugin.install = function (Vue, options) {
    
    
  // 1. 添加全局方法或 property
  Vue.myGlobalMethod = function () {
    
    
    // 逻辑...
  }

  // 2. 添加全局资源
  Vue.directive('my-directive', {
    
    
    bind (el, binding, vnode, oldVnode) {
    
    
      // 逻辑...
    }
    ...
  })

  // 3. 注入组件选项
  Vue.mixin({
    
    
    created: function () {
    
    
      // 逻辑...
    }
    ...
  })

  // 4. 添加实例方法
  Vue.prototype.$myMethod = function (methodOptions) {
    
    
    // 逻辑...
  }
}

demo

  • js代码
(function () {
    
    
    // 需要向外暴露插件对象
    const MyPlugin = {
    
    };
    // 插件对象必须有一个install方法
    MyPlugin.install = function (Vue, options) {
    
    
        // 1. 添加全局方法或属性
        Vue.myGlobalMethod = function () {
    
    
            console.log('Vue函数对象的方法myGlobalMethod()');
        };
        // 2. 添加全局资源
        Vue.directive('my-directive', function(el, binding) {
    
    
            el.textContent = binding.value.toUpperCase();
        })
        // 3. 注入组件选项
        // 4. 添加实例方法
        Vue.prototype.$myMethod = function () {
    
    
            console.log("Vue实例对象的方法$myMethod()")
        }  
    }
    // 向外暴露
    window.MyPlugin = MyPlugin;
})()
  • html代码
<body>
    <div id="test">
        <p v-my-directive="msg"></p>
    </div>

    <script src="../js/vue.js"></script>
    <script src="./15Vue-myPlugin.js"></script>
    <script>
        //声明使用插件
        Vue.use(MyPlugin); // 内部会执行MyPlugin.install(Vue)
        Vue.myGlobalMethod();
        
        const vm = new Vue({
     
     
            el: "#test",
            data: {
     
     
                msg: "Hello, YK~"
            }
        });
        
        vm.$myMethod();

    </script>
</body>
  • 运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44972008/article/details/113179195