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

前端 未结 7 1825
北荒
北荒 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:11

    Great question. In my research I found vue-inject can handle this in the best way. I have many function libraries (services) kept separate from standard vue component logic handling methods. My choice is to have component methods just be delegators that call the service functions.

    https://github.com/jackmellis/vue-inject

    0 讨论(0)
  • 2020-12-07 19:17

    inside any component without having to first import them and then prepend this to the function name

    What you described is mixin.

    Vue.mixin({
      methods: {
        capitalizeFirstLetter: str => str.charAt(0).toUpperCase() + str.slice(1)
      }
    })
    

    This is a global mixin. with this ALL your components will have a capitalizeFirstLetter method, so you can call this.capitalizeFirstLetter(...) from component methods or you can call it directly as capitalizeFirstLetter(...) in component template.

    Working example: http://codepen.io/CodinCat/pen/LWRVGQ?editors=1010

    See the documentation here: https://vuejs.org/v2/guide/mixins.html

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-07 19:26

    Create a new mixin:

    "src/mixins/generalMixin.js"

    Vue.mixin({
      methods: {
        capitalizeFirstLetter(str) {
            return str.charAt(0).toUpperCase() + str.slice(1);
        }    
      }
    })
    

    Then import it into your main.js like:

    import '@/mixins/generalMixin'
    

    From now on you will be able to use the function like this.capitalizeFirstLetter(str) within your component script or without this in a template. i.e.:

    <template>
        <div>{{ capitalizeFirstLetter('hello') }}</div>
    </template>
    

    Using with <script />, you have to use this because you mixed a method into the main Vue instance. If there are ways of removing this it will probably involve something unconventional, this at least is a documented way of sharing functions which will be easy to understand for any future Vue devs to your project.

    0 讨论(0)
  • 2020-12-07 19:30

    Use a global filter if it only concerns how data is formatted when rendered. This is the first example in the docs:

    {{ message | capitalize }}
    
    Vue.filter('capitalize', function (value) {
      if (!value) return ''
      value = value.toString()
      return value.charAt(0).toUpperCase() + value.slice(1)
    })
    
    0 讨论(0)
  • 2020-12-07 19:34

    Using Webpack v4

    Create a separate file for readability (just dropped mine in plugins folder). Reproduced from @CodinCat and @digout responses

    //resources/js/plugins/mixin.js
    import Vue from 'vue'
    
    Vue.mixin({
        methods: {
          capitalizeFirstLetter: str => str.charAt(0).toUpperCase() + str.slice(1),
          sampleFunction(){
            alert('Global Functions')
          }
        }
      })
    

    Then import in your main.js or app.js file

    //app.js
    import mixin from './plugins/mixin' 
    

    USAGE:

    Call this.sampleFunction() or this.capitalizeFirstLetter()

    0 讨论(0)
提交回复
热议问题