基本介绍
-
功能:增强Vue
-
本质
- 包含 install 方法的一个对象,install 的第一个参数是 Vue,其他参数是插件使用者传递的数据
- 将各种功能(方法),汇集到一个文件里面
定义插件
```
// 在 src 目录下,创建 plugins.js
// 需要对外暴露,才能让别的组件使用
export default install(Vue, options) {
// 1.添加全局指令
Vue.directive(...)
// 2.添加全局混入
Vue.mixin(...)
// 3.添加实例方法
Vue.prototype.xxx = ()=>{...}
}
```
使用插件
```
// 在 main.js
// 引入插件
import xxx from './plugins'
// 使用插件
Vue.use(xxx)
```
代码实现
plugins.js
```
export default {
install(Vue) {
// 在 Vue 原型上添加一个方法(vm 和 vc 都能用了)
Vue.prototype.print = ()=>{
alert('Hello plugins 插件')
}
}
}
```
main.js
```
import Vue from 'vue'
import App from './App.vue'
// 引入插件
import plugins from './plugins'
// 关闭生产提示
Vue.config.productionTip = false
// 使用插件
Vue.use(plugins)
new Vue({
el: '#app',
render: h => h(App),
})
```
School.vue
```
<template>
<div class="container">
<button @click="test">点我测试插件的print方法</button>
</div>
</template>
<script>
// 对外暴露
export default {
name: 'School',
methods: {
test() {
this.print()
}
}
}
</script>
```