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

前端 未结 7 1855
北荒
北荒 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: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.:

    
    

    Using with

提交回复
热议问题