Search code examples
vue.jscomponents

vue component to use common functions


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>

Solution

  • 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