美文网首页
Vue插件:use

Vue插件:use

作者: fanren | 来源:发表于2022-07-19 11:12 被阅读0次

    本章节以添加全局实例方法的方式引入插件为例

    一、为什么用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')
        }
      }
    }
    

    相关文章

      网友评论

          本文标题:Vue插件:use

          本文链接:https://www.haomeiwen.com/subject/furdirtx.html