How to isolate reusable small functions in vuejs

Viewed 977

I have a function that let's say generates a random string for generating a token. I have this function in my methods:{} and I use it in my div without any problem.

But I am trying to put this function in it's own separate file so I can import it for future use, so I put a functions.js file inside my src like this:

// /src/functions.js
export default {
    // generate tokes
  tokenGenerator () { ... }

}

And in my src/components/foo.vue I am importing this file (no issues with importing)

<template>
 <div> {{ tokenGenerator }} </div>
</template>

<script>
import tokenGenerator from '../../functions'
export default {
   data() {
      return ;
   }
}
</script>

This should work, but it doesn't. Importing is not the issue, but something else.. the console error shows me that It can not find function tokenGenerator

2 Answers

For one, you seem to be trying to import a single function, but tokenGenerator in your code is a reference to the whole object exported in your functions file.

Secondly, you cannot access plain javascript functions using Vue interpolation {{ ... }}. The template can only reference functions defined as methods on the related Vue instance.

You can use a mixin to do what you want:

// /src/functions.js
export default {
  methods: {
    // generate tokens
    tokenGenerator () { ... }
  }
}

<!>

<template>
  <div>{{ tokenGenerator }} </div>
</template>

<script>
import mixinFuncs from '../../functions'
export default { 
   mixins: [ mixinFuncs ],
}
</script>

Here's the documentation on mixins.


If you simply need access to the tokenGenerator function in your Vue script, then you can export it directly and import it:

// /src/functions.js
// generate tokens
export const tokenGenerator = () => { 
  //... 
}

<!>

<template>
  <div> {{ token }} </div>
</template>

<script>
import { tokenGenerator } from '../../functions'

export default {
  data() {
    return {
      token: tokenGenerator()
    }
  }
}
</script>

Here's a working example.

Export it in this way in functions.js:

export class util {
    static tokenGenerator() {
       //do your stuff here
    }
}

In foo.vue:

<template>
  <div>{{ tokenGenerator }} </div>
</template>

<script>
import { util } from '../../functions';

export default {
  data() {
    return {
       textData: util.tokenGenerator
    }
  } 
}
</script>
Related