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

旧街凉风 提交于 2019-12-17 22:33:14

问题


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, that contains a bunch of general-purpose functions, such as capitalizing the first letter of a string. This file looks like this:

export default {
    capitalizeFirstLetter(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }
}

My main.js file initializes the app:

import Vue from 'vue'
import VueResource from "vue-resource"
import store from "./store"
import Router from "./router"
import App from "./components/App.vue"

Vue.use(VueResource)

const app = new Vue({
    router: Router,
    store,
    template: '<app></app>',
    components: { App }
}).$mount('#app')

My App.vue file contains the template:

<template>
    <navbar></navbar>
    <div class="container">
        <router-view></router-view>
    </div>
</template>

<script>
export default {
    data() {
        return {
            //stuff
        }
    }
}
</script>

I then have a bunch of single-file components, which Vue-Router handles navigating to inside the <router-view> tag in the App.vue template.

Now let's say that I need to use the capitalizeFirstLetter() function inside a component that is defined in SomeComponent.vue. In order to do this, I first need to import it:

<template>Some Component</template>

<script>
import {capitalizeFirstLetter} from '../helpers.js'
export default {
    data() {
        return {
            myString = "test"
        }
    },
    created() {
         var newString = this.capitalizeFirstLetter(this.myString)
    }
}
</script>

This becomes a problem quickly because I end up importing the function into many different components, if not all of them. This seems repetitive and also makes the project harder to maintain. For example if I want to rename helpers.js, or the functions inside it, I then need to go into every single component that imports it and modify the import statement.

Long story short: how do I make the functions inside helpers.js globally available so that I can call them inside any component without having to first import them and then prepend this to the function name? I basically want to be able to do this:

<script>
export default {
    data() {
        return {
            myString = "test"
        }
    },
    created() {
         var newString = capitalizeFirstLetter(this.myString)
    }
}
</script>

回答1:


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




回答2:


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




回答3:


Create a new mixin:

"src/mixins/generalMixin.js"

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

The import it into your main.js like:

import '@/src/mixins/generalMixin'

From now on you will be able to use the function like this.capitalizeFirstLetter(str).

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.




回答4:


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




回答5:


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)
})


来源:https://stackoverflow.com/questions/42613061/vue-js-making-helper-functions-globally-available-to-single-file-components

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