一、前言
插件 (Plugins) 是一种能为 Vue 添加全局功能的工具代码。
本文主要介绍了vue中 plugin插件的用法及其功能。
二、用法
定义plugin需要使用 install 方法。这个方法有两个参数app、options(可选)
const myPlugin = {
install(app, options){
console.log(app, options);
}
}
app.use(myPlugin,{name: '张三'})
打开控制台看看app, options分别会输出什么内容:
从图中可以看出,app包含有directive自定义指令、mixin混入以及config配置等内容,options里面是使用插件传入的{ name: ‘张三’ }
三、例子
1、添加directive
plugin.js:
// plugin.js
export const myPlugin = {
install(Vue) {
Vue.directive('focus', {
inserted(el,bindings){
el.value = bindings.value
el.focus()
}
})
}
}
main.js:
import Vue from 'vue'
import App from './App.vue'
import { myPlugin } from './plugins'
Vue.config.productionTip = false
// 使用插件
Vue.use(myPlugin)
new Vue({
render: h => h(App),
}).$mount('#app')
demo.vue:
<template>
<div>
<span >{{ msg }}</span>
<input type="text" v-focus="msg">
</div>
</template>
<script>
export default {
data: () => ({}),
props: ["msg"],
};
</script>
2、添加mixin
export const myPlugin = {
install(Vue) {
Vue.directive('focus', {
inserted(el,bindings){
el.value = bindings.value
el.focus()
}
})
Vue.mixin({
mounted(){
console.log('mixin');
}
})
}
}
控制台成功输出:mixin
3、添加config
export const myPlugin = {
install(Vue) {
Vue.directive('focus', {
inserted(el,bindings){
el.value = bindings.value
el.focus()
}
})
Vue.mixin({
mounted(){
console.log('mixin');
}
})
// 定义一个实例方法,定义在Vue的原型上 Vue.prototype.xxx
Vue.prototype.message = function(val){
console.log(val);
}
//定义一个过滤器
Vue.filter('fmtDate', function(val){
return moment(val).format('YYYY-MM-DD')
});
Vue.config.globalProperties.$sayHello = 'hello';
}
}
在组件中:
console.log(this.$sayHello )