一、插件封装
1、在Vue生态中,除了Vue本身,其它所有的与Vue相关的第三方包,都是插件
例子:
import VueRouter form 'vue-router'
Vue.use(VueRouter) // 注册插件
2、如何封装Vue插件
(1)第一种写法
const Plugin = { install (Vue) { //do something} }
(2)第二种写法
const Plugin = function (Vue) {}
3、如何使用插件
Vue.use(Plugin)
调用插件上的install方法,并传入Vue实参。
4、插件的作用
插件是一种更加高级的代码复用技术,可以以插件的方式为我们提供可复用的组件、混入、指令、过滤器、原型链API等等。
二、例子代码
<html>
<head><title>插件封装</title><style></style>
</head>
<body><div id="app"><my-button></my-button><h1>{{ "99.1" | rmb }}</h1><h1 v-color='"red"'>测试</h1></div><script src="https://cdn.jsdelivr.net/npm/vue@2.7.16/dist/vue.js"></script><script>const MyPlugin = {install: function(Vue) {// 插件中可以全局混入Vue.mixin({data() {return {version: 'v2'}}})// 插件中可以定义全局组件Vue.component('my-button', {template: `<div>我的按钮</div>`})// 插件中可以定义全局过滤器Vue.filter('rmb', val=>('¥'+val))// 插件中可以定义全局指令Vue.directive('color', function(el,binding){el.style.color = binding.value})// 插件中可以操作Vue的原型链Vue.prototype.$ajax = function(url,method,data) {console.log('---调接口')}}}Vue.use(MyPlugin)const app = new Vue({mounted() {console.log('---version', this.version)console.log('---$ajax', this.$ajax)}})app.$mount('#app')</script></body>
</html>