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

大城市里の小女人 提交于 2019-11-28 17:44:29

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(...)

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

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

Hammerbot

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

EDIT March 1st 2018:

The official way to make a plugin is to create an object with an install function:

import Vue from 'vue'
import helpers from './helpers'

const plugin = {
    install () {
        Vue.helpers = helpers
        Vue.prototype.$helpers = helpers
    }
}

Vue.use(plugin)

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

Old response:

import helpers from './helpers';
export default (Vue) => {
    Object.defineProperties(Vue.prototype, {
        $helpers: {
            get() {
                return helpers;
            }
        }
    });
};

Then, in your main.js file:

import Vue from 'vue'
import helpersPlugin from './helpersPlugin';

Vue.use(helpersPlugin);

Source: https://gist.github.com/logaretm/56126af5867e391ea9507b462259caf3

user2090357

Import it in the main.js file just like 'store' and you can access it in all the components.

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  render: h => h(App)
})

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!