Vue系列二:Plugin

vue支持plugin用法,比如引用一些比较流行的Component库 Element-UI、iView等等,这里总结下Plugin的封装。

  • src目录下创建plugins目录存放各种plugin。

ElementUI 按需引入

  • 借助 babel-plugin-component,我们可以只引入需要的组件,以达到减小项目体积的目的。
    首先,安装 babel-plugin-component
1
npm install babel-plugin-component -D
  • .babelrcbabel.config.js 修改为:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// babel.config.js
module.exports = {
presets: [
'@vue/app',
],
plugins: [
[
'component',
{
libraryName: 'element-ui',
styleLibraryName: 'theme-chalk',
},
],
],
};
  • 在plugins目录下创建element-ui.js, 在里面引入要用到的组件即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// element-ui.js
import { DatePicker, Transfer } from 'element-ui';

function plugin(Vue) {
Vue.component(DatePicker.name, DatePicker);
Vue.component(Transfer.name, Transfer);
}

// Install by default if using the script tag
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(plugin);
}

export default plugin;
  • main.js引入plugin, 在main.js里引入的各个模块的时候, 推荐分块引入, 并注释。
1
2
// vue plugins
import ElementUI from '@/view/plugins/element-ui';

封装一个alert plugin

  • alert插件的方法挂在到Vue原型上即可, 代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// vue-tada.js
import swal from 'sweetalert';

function plugin(Vue) {
Vue.prototype.$tada = swal;
Vue.prototype.$tada.success = function success(title, text = '') {
return swal({
title,
text,
icon: 'success',
button: '确认',
});
};
Vue.prototype.$tada.error = function error(title, text = '') {
if (typeof text === 'object') {
text = JSON.stringify(text);
}
return swal({
title,
text,
icon: 'error',
button: '确认',
});
};
Vue.prototype.$tada.confirm = function danger(config) {
const {
title,
text,
icon = 'warning',
dangerMode = true,
primaryText = '删除',
} = config;
return swal({
title,
text,
icon,
closeOnClickOutside: false,
buttons: ['取消', primaryText],
dangerMode,
});
};
}

// Install by default if using the script tag
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(plugin);
}

export default plugin;
  • 相同的,在main.js里引入即可
1
2
// vue plugins
import VueTada from '@/view/plugins/vue-tada';
  • 全局使用:
1
2
3
4
5
6
7
8
this.$tada.confirm({
title: 'titleName',
text: 'some text',
}).then(ok => {
if (ok) {
// some operations.
}
});

V-Chat

1
2
3
4
5
6
7
8
9
10
// v-chat.js
import VeLine from 'v-charts/lib/line.common';

function install(Vue) {
Vue.component(VeLine.name, VeLine);
}

export default {
install,
};

更多Plugin请移步awesome-vue