本章节以添加全局实例方法的方式引入插件为例
一、为什么用use
通过添加全局实例方法引入插件的时候,我们可以再main.js
中直接添加;
Vue.prototype.$dateFormat = dateFormat;
但是,如果有10个方法,需要引入呢?是不是意味着main.js
中需要引入10次;
Vue.prototype.$dateFormat = dateFormat;
Vue.prototype.$dateFormat1 = dateFormat1;
Vue.prototype.$dateFormat2 = dateFormat2;
......
那对于使用该插件的人来说,是不是太不友好了?开发者看到这样的插件,都会望而却步的。
此时use
的作用就体现出来了。
二、创建插件
创建一个插件DateFormatter.js
import moment from "moment";
function dateFormat(date, format) {
return moment(date).format(format);
}
const install = function (Vue, options) {
Vue.prototype.$dateFormat = dateFormat;
};
export default { install };
- 该插件必须要有一个
install
方法,这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象: - 需要在
install
方法内部,给vue添加全局实例方法(或全局混入,添加过滤器)
二、引入插件
在main.js
文件中,引入插件DateFormatter
import DateFormatter from './DateFormatter.js'
Vue.use(DateFormatter);
可直接通过use
引入插件;
使用
use
引入插件,插件使用者,只需要关心插件的具体使用,而不需要关心插件该怎么引入;
三、插件的使用
export default {
name: 'App',
data() {
return {
date: new Date
}
},
computed: {
currentDate() {
// 使用该全局的实例方法
return this.$dateFormat(this.date, 'YYYY-MM')
}
}
}
网友评论