Reputation: 961
I'm looking to get a handle on the Vue CLI3 project system. Currently refactoring a long single html file of in-line vue into real '.vue' components. One goal is to use some common functions among my vue components for various things. In my common-functions.js file I've got something like this:
function capitalize(str) {
return str[0].toUpperCase() + str.substr(1, );
};
And in my HelloWorld.vue file I've got this and it's not working through many various attempts. All searches I find seem to be dealing with other things, surely there's an easy way to just use some common functions, right??
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<ul>
<li v-for='c in categoryNames'>{{ c }}</li>
</ul>
</div>
</template>
<script>
require('../js/common-functions.js');
export default {
name: 'HelloWorld',
data () {
return {
msg: capitalize('welcome to Your Vue.js App!'),
categoryNames : this.$root.categoryNames
}
}
}
</script>
Of course the message is:
[Vue warn]: Error in data(): "ReferenceError: capitalize is not defined"
found in
---> <HelloWorld> at src/components/HelloWorld.vue
<App> at src/App.vue
<Root>
Upvotes: 1
Views: 8197
Reputation: 10729
One Solution:
Register your global functions to Vue.prototype
by Vue.use().
Like below demo:
let myGlobalAPIGroup1 = { // API Group 1
install: function (_Vue) {
if(!_Vue.prototype.$apiGroup1) {
_Vue.prototype.$apiGroup1 = {}
}
_Vue.prototype.$apiGroup1.capitalize = function (str) {
return str[0].toUpperCase() + str.substr(1, );
}
}
}
let myGlobalAPIGroup2 = { // API Group 2
install: function (_Vue) {
if(!_Vue.prototype.$apiGroup2) {
_Vue.prototype.$apiGroup2 = {}
}
_Vue.prototype.$apiGroup2.capitalize = function (str) {
return str[0].toUpperCase() + str.substr(1, ) + '@';
}
}
}
Vue.use(myGlobalAPIGroup1) //register
Vue.use(myGlobalAPIGroup2) //register
new Vue({
el: '#app',
data() {
return {
testValues: ['label a', 'label b'],
}
},
methods:{
testAPI1: function(item) {
return this.$apiGroup1.capitalize(item)
},
testAPI2: function(item) {
return this.$apiGroup2.capitalize(item)
}
}
})
#app > div {
display: inline-block;
margin-left: 5px;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<div>
<h3>Group 1:</h3>
<p v-for="(item, index) in testValues" :key="index">{{testAPI1(item)}}</p>
</div>
<div>
<h3>Group 2:</h3>
<p v-for="(item, index) in testValues" :key="index">{{testAPI2(item)}}</p>
</div>
</div>
Upvotes: 1
Reputation: 214957
At the end of common-functions.js
, export the function:
export default capitalize;
And in the HelloWorld.vue
, import it with:
import capitalize from '../js/common-functions.js';
// this should replace the require line
Upvotes: 4