Vue.js-使助手功能全局可用于单个文件组件

我有一个Vue 2项目,其中有许多(50+)个单文件组件我将Vue-Router用于路由,将Vuex用于状态。

有一个名为helpers.js的文件,其中包含许多通用功能,例如将字符串的首字母大写。该文件如下所示:

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

我的main.js文件初始化了应用程序:

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

我的App.vue文件包含模板:

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

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

然后,我有一堆单文件组件,Vue-Router负责处理这些文件,并导航到<router-view>App.vue模板中标记

现在,我们需要capitalizeFirstLetter()SomeComponent.vue中定义的组件内使用该函数为此,我首先需要导入它:

<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>
神奇老丝2020/03/10 14:05:28

在任何组件内部,而无需先导入它们,然后在其前面加上函数名称

您描述的是mixin

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

这是全局混合。这样,您的所有组件都会有一个capitalizeFirstLetter方法,因此您可以调用this.capitalizeFirstLetter(...)

工作示例:http : //codepen.io/CodinCat/pen/LWRVGQ?editors=1010

请参阅此处的文档:https : //vuejs.org/v2/guide/mixins.html

乐米亚2020/03/10 14:05:27

好问题。在我的研究中,我发现vue-inject可以以最佳方式处理此问题。我有许多功能库(服务)与标准vue组件逻辑处理方法分开。我的选择是让组件方法成为调用服务函数的委托人。

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