Vue14 -- 自定义插件

第一步:创建js文件vue-myself.js

//Vue插件库
(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. 注入组件选项
//	  Vue.mixin({
//	    created: function () {
//	      // 逻辑...
//	    }
//	    ...
//	  })
	
	  // 4. 添加实例方法
	  Vue.prototype.$myMethod = function (methodOptions) {
	    // 逻辑...
	    console.log('Vue实例对象的方法$myMethod()')
	  }
	}
	
	window.MyPlugin = MyPlugin
})()

  第二步:使用插件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<div id="app">
			<!--使用全局资源 ---  自定义指令-->
			<p v-my-directive = 'msg'></p>  
		</div>
		
		<script src="https://vuejs.org/js/vue.js"></script>
		<script src="js/vue-myself.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			//声明使用插件
			Vue.use(MyPlugin) // 内部执行MyPlugin.install(Vue)
			
			
			Vue.myGlobalMethod() //调用全局方法或属性
			
			var app = new Vue({
				el:'#app',
				data:{
					msg:'I like U'
				}
			})
			
			app.$myMethod() // 调用实例方法
		</script>
	</body>
</html>

  

原文地址:https://www.cnblogs.com/lee-xingxing/p/11216912.html