插件js文件

(function(){

    //声明 MyPlugin 插件对象
    const MyPlugin = {}
    MyPlugin.install = function (Vue, options) {
        // 1. 添加全局方法或属性
        Vue.myGlobalMethod = function () {
          alert('MyPlugin.myGlobalMethod全局方法调用了')
        }
      
        // 2. 添加全局指令
        Vue.directive('my-directive', {
          inserted (el, binding) {
              el.innerHTML = "MyPlugin.my-directive指令被调用了" + binding.value
          }
        })

        // 3. 添加实例方法 new Vue()
        Vue.prototype.$myMethod = function (value) {
            alert('Vue 实例方法myMethod被调用了:' + value)
        }
      }

      //将插件添加 到 window对象
      window.MyPlugin = MyPlugin

})()

使用插件html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>自定义插件</title>
</head>
<body>
    <div id="app">
        <span v-my-directive="content">  </span>
    </div>
    <script src="node_modules/vue/dist/vue.js"></script>
    <!-- 要引入在vue.js下面 -->
    <script src="js/plugins.js"></script>
    <script>
        //1. 引入插件MyPlugin, 其实就是安装 MyPlugin 插件
        Vue.use(MyPlugin)

        var vm = new Vue({
            el: '#app',
            data: {
                content: 'hello'
            }
        })
        //调用插件中的实例 方法,注意是vm调用,不是Vue
        // 注意,不要少了 $
        vm.$myMethod('mengxuegu')

        //调用全局方法,注意是 Vue进行调用,不是vm
        Vue.myGlobalMethod()

    </script>
</body>
</html>
Logo

前往低代码交流专区

更多推荐