Vue.js - Making helper functions globally available to single-file components

前端 未结 7 1849
北荒
北荒 2020-12-07 18:38

I have a Vue 2 project that has many (50+) single-file components. I use Vue-Router for routing and Vuex for state.

There is a file, called helpers.js

7条回答
  •  被撕碎了的回忆
    2020-12-07 19:24

    Otherwise, you could try to make your helpers function a plugin:

    import Vue from 'vue'
    import helpers from './helpers'
    
    const plugin = {
      install () {
        Vue.helpers = helpers
        Vue.prototype.$helpers = helpers
      }
    }
    
    Vue.use(plugin)
    

    In your helper.js export your functions, this way:

    const capFirstLetter = (val) => val.charAt(0).toUpperCase() + val.slice(1);
    const img2xUrl = (val) => `${val.replace(/(\.[\w\d_-]+)$/i, '@2x$1')} 2x`;
    
    export default { capFirstLetter, img2xUrl };
    

    or

    export default { 
      capFirstLetter(val) {
        return val.charAt(0).toUpperCase() + val.slice(1);
      },
      img2xUrl(val) {
        return `${val.replace(/(\.[\w\d_-]+)$/i, '@2x$1')} 2x`;
      },
    };
    

    You should then be able to use them anywhere in your components using:

    this.$helpers.capitalizeFirstLetter()

    or anywhere in your application using:

    Vue.helpers.capitalizeFirstLetter()

    You can learn more about this in the documentation: https://vuejs.org/v2/guide/plugins.html

提交回复
热议问题