我有一个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>
您描述的是mixin。
这是全局混合。这样,您的所有组件都会有一个
capitalizeFirstLetter
方法,因此您可以调用this.capitalizeFirstLetter(...)
工作示例:http : //codepen.io/CodinCat/pen/LWRVGQ?editors=1010
请参阅此处的文档:https : //vuejs.org/v2/guide/mixins.html