Vue.js - 使辅助函数对单文件组件全局可用
Vue.js - Making helper functions globally available to single-file components
我有一个包含许多 (50+) single-file components 的 Vue 2 项目。我使用 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 处理导航到 App.vue 模板中的 <router-view>
标签内。
现在假设我需要在 SomeComponent.vue 中定义的组件中使用 capitalizeFirstLetter()
函数。为此,我首先需要导入它:
<template>Some Component</template>
<script>
import {capitalizeFirstLetter} from '../helpers.js'
export default {
data() {
return {
myString = "test"
}
},
created() {
var newString = this.capitalizeFirstLetter(this.myString)
}
}
</script>
这很快就会成为一个问题,因为我最终将该函数导入到许多不同的组件中,如果不是全部的话。这似乎是重复的,也使项目更难维护。例如,如果我想重命名 helpers.js 或其中的函数,那么我需要进入导入它的每个组件并修改导入语句。
长话短说:如何使 helpers.js 全局 中的函数可用,以便我可以在内部调用它们任何组件而不必先导入它们然后在函数名称前添加this
?我基本上希望能够做到这一点:
<script>
export default {
data() {
return {
myString = "test"
}
},
created() {
var newString = capitalizeFirstLetter(this.myString)
}
}
</script>
否则,您可以尝试让您的助手功能成为一个插件:
import Vue from 'vue'
import helpers from './helpers'
const plugin = {
install () {
Vue.helpers = helpers
Vue.prototype.$helpers = helpers
}
}
Vue.use(plugin)
在你的 helper.js
中导出你的函数,这样:
const capFirstLetter = (val) => val.charAt(0).toUpperCase() + val.slice(1);
const img2xUrl = (val) => `${val.replace(/(\.[\w\d_-]+)$/i, '@2x')} 2x`;
export default { capFirstLetter, img2xUrl };
或
export default {
capFirstLetter(val) {
return val.charAt(0).toUpperCase() + val.slice(1);
},
img2xUrl(val) {
return `${val.replace(/(\.[\w\d_-]+)$/i, '@2x')} 2x`;
},
};
然后您应该能够在您的组件中的任何地方使用它们:
this.$helpers.capitalizeFirstLetter()
或在您的应用程序中的任何地方使用:
Vue.helpers.capitalizeFirstLetter()
您可以在文档中了解更多相关信息:https://vuejs.org/v2/guide/plugins.html
inside any component without having to first import them and then prepend this to the function name
你描述的是mixin.
Vue.mixin({
methods: {
capitalizeFirstLetter: str => str.charAt(0).toUpperCase() + str.slice(1);
}
})
这是一个全局混合。有了这个,你所有的组件都会有一个 capitalizeFirstLetter
方法,所以你可以从组件方法调用 this.capitalizeFirstLetter(...)
或者你可以在组件模板中直接调用它作为 capitalizeFirstLetter(...)
。
好问题。在我的研究中,我发现 vue-inject 可以以最好的方式处理这个问题。我有许多函数库(服务)与标准的 vue 组件逻辑处理方法分开。我的选择是让组件方法只是调用服务函数的委托者。
像'store'一样将其导入main.js文件,您可以在所有组件中访问它。
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)
})
创建一个新的 mixin:
"src/mixins/generalMixin.js"=18=]
Vue.mixin({
methods: {
capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
}
})
然后将其导入到您的 main.js 中,例如:
import '@/mixins/generalMixin'
从现在开始,您将能够在组件脚本中或在模板中不使用 this
的情况下使用类似 this.capitalizeFirstLetter(str)
的功能。即:
<template>
<div>{{ capitalizeFirstLetter('hello') }}</div>
</template>
你必须使用 this
因为你在主 Vue 实例中混合了一个方法。如果有删除 this
的方法,它可能会涉及一些非常规的东西,这至少是一个 documented way 共享功能,对于您项目的任何未来 Vue 开发人员来说,这将很容易理解。
Using Webpack v4
创建一个单独的文件以提高可读性(只是将我的放在插件文件夹中)。
转载自@CodinCat 和@digout 回复。
//resources/js/plugins/mixin.js
import Vue from 'vue';
Vue.mixin({
methods: {
capitalizeFirstLetter: str => str.charAt(0).toUpperCase() + str.slice(1),
sampleFunction() {
alert('Global Functions');
},
}
});
然后,导入您的 main.js 或 app.js 文件。
//app.js
import mixin from './plugins/mixin';
用法:
致电this.sampleFunction()
或this.capitalizeFirstLetter()
。
如果只涉及数据在呈现时的格式设置,请使用全局过滤器。这是 docs:
中的第一个例子
{{ message | capitalize }}
Vue.filter('capitalize', function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})
我有一个包含许多 (50+) single-file components 的 Vue 2 项目。我使用 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 处理导航到 App.vue 模板中的 <router-view>
标签内。
现在假设我需要在 SomeComponent.vue 中定义的组件中使用 capitalizeFirstLetter()
函数。为此,我首先需要导入它:
<template>Some Component</template>
<script>
import {capitalizeFirstLetter} from '../helpers.js'
export default {
data() {
return {
myString = "test"
}
},
created() {
var newString = this.capitalizeFirstLetter(this.myString)
}
}
</script>
这很快就会成为一个问题,因为我最终将该函数导入到许多不同的组件中,如果不是全部的话。这似乎是重复的,也使项目更难维护。例如,如果我想重命名 helpers.js 或其中的函数,那么我需要进入导入它的每个组件并修改导入语句。
长话短说:如何使 helpers.js 全局 中的函数可用,以便我可以在内部调用它们任何组件而不必先导入它们然后在函数名称前添加this
?我基本上希望能够做到这一点:
<script>
export default {
data() {
return {
myString = "test"
}
},
created() {
var newString = capitalizeFirstLetter(this.myString)
}
}
</script>
否则,您可以尝试让您的助手功能成为一个插件:
import Vue from 'vue'
import helpers from './helpers'
const plugin = {
install () {
Vue.helpers = helpers
Vue.prototype.$helpers = helpers
}
}
Vue.use(plugin)
在你的 helper.js
中导出你的函数,这样:
const capFirstLetter = (val) => val.charAt(0).toUpperCase() + val.slice(1);
const img2xUrl = (val) => `${val.replace(/(\.[\w\d_-]+)$/i, '@2x')} 2x`;
export default { capFirstLetter, img2xUrl };
或
export default {
capFirstLetter(val) {
return val.charAt(0).toUpperCase() + val.slice(1);
},
img2xUrl(val) {
return `${val.replace(/(\.[\w\d_-]+)$/i, '@2x')} 2x`;
},
};
然后您应该能够在您的组件中的任何地方使用它们:
this.$helpers.capitalizeFirstLetter()
或在您的应用程序中的任何地方使用:
Vue.helpers.capitalizeFirstLetter()
您可以在文档中了解更多相关信息:https://vuejs.org/v2/guide/plugins.html
inside any component without having to first import them and then prepend this to the function name
你描述的是mixin.
Vue.mixin({
methods: {
capitalizeFirstLetter: str => str.charAt(0).toUpperCase() + str.slice(1);
}
})
这是一个全局混合。有了这个,你所有的组件都会有一个 capitalizeFirstLetter
方法,所以你可以从组件方法调用 this.capitalizeFirstLetter(...)
或者你可以在组件模板中直接调用它作为 capitalizeFirstLetter(...)
。
好问题。在我的研究中,我发现 vue-inject 可以以最好的方式处理这个问题。我有许多函数库(服务)与标准的 vue 组件逻辑处理方法分开。我的选择是让组件方法只是调用服务函数的委托者。
像'store'一样将其导入main.js文件,您可以在所有组件中访问它。
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)
})
创建一个新的 mixin:
"src/mixins/generalMixin.js"=18=]
Vue.mixin({
methods: {
capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
}
})
然后将其导入到您的 main.js 中,例如:
import '@/mixins/generalMixin'
从现在开始,您将能够在组件脚本中或在模板中不使用 this
的情况下使用类似 this.capitalizeFirstLetter(str)
的功能。即:
<template>
<div>{{ capitalizeFirstLetter('hello') }}</div>
</template>
你必须使用 this
因为你在主 Vue 实例中混合了一个方法。如果有删除 this
的方法,它可能会涉及一些非常规的东西,这至少是一个 documented way 共享功能,对于您项目的任何未来 Vue 开发人员来说,这将很容易理解。
Using Webpack v4
创建一个单独的文件以提高可读性(只是将我的放在插件文件夹中)。 转载自@CodinCat 和@digout 回复。
//resources/js/plugins/mixin.js
import Vue from 'vue';
Vue.mixin({
methods: {
capitalizeFirstLetter: str => str.charAt(0).toUpperCase() + str.slice(1),
sampleFunction() {
alert('Global Functions');
},
}
});
然后,导入您的 main.js 或 app.js 文件。
//app.js
import mixin from './plugins/mixin';
用法:
致电this.sampleFunction()
或this.capitalizeFirstLetter()
。
如果只涉及数据在呈现时的格式设置,请使用全局过滤器。这是 docs:
中的第一个例子{{ message | capitalize }}
Vue.filter('capitalize', function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})