自定義插件
說明
1) Vue 插件是一個包含 install 方法的對象
2) 通過 install 方法給 Vue 或 Vue 實例添加方法, 定義全局指令等
/*** 自定義 Vue 插件 */
(function () {
const MyPlugin = {}
MyPlugin.install = function (Vue, options) {
// 1. 添加全局方法或屬性
Vue.myGlobalMethod = function () {
alert('Vue 函數對象方法執行')
} // 2. 添加全局資源
Vue.directive('my-directive', function (el, binding) {
el.innerHTML = "MyPlugin my-directive " + binding.value
}) // 3. 添加實例方法
Vue.prototype.$myMethod = function () {
alert('vue 實例對象方法執行')
}
}
window.MyPlugin = MyPlugin
})()
<script type="text/javascript" src="vue-myPlugin.js"></script>
<script type="text/javascript">
//使用自定義插件
Vue.use(MyPlugin)
var vm = new Vue({
el: '#demo',
data: {
msg: 'atguigu'
}
})
//調用自定義的靜態方法
Vue.myGlobalMethod()
//調用自定義的對象方法
vm.$myMethod()
</script>
</html>