Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a function to a Vue component?

I am trying to import a single function to my Vue component. I've created a separated js file for my function:

randomId.js:

exports.randomId = () => //My function ...

In my Vue component, I've imported the Random js:

let randomId = require('../functions/randomId');
randomId();

but Webpack throws an error of "randomId is not a function". I tried to import the file using import syntax, but the error remains.

import randomId from '../functions/randomId';

Should I use some other methods for importing single functions? I'm relatively new to Webpack and JS6.

like image 448
Negar Avatar asked Aug 09 '18 18:08

Negar


People also ask

Can you pass functions as props in Vue?

You can pass strings, arrays, numbers, and objects as props. But can you pass a function as a prop? While you can pass a function as a prop, this is almost always a bad idea. Instead, there is probably a feature of Vue that is designed exactly to solve your problem.

How do I import Vue component into Vue component?

STEP 01: First, Import the Child Component into the Parent Component inside script tag but above export default function declaration. STEP 02: Then, Register the Child Component inside the Parent Component by adding it to components object. STEP 03: Finally, Use the Child Component in the Parent Component Template.

How do I import files into Vue?

You need to import the vue-multiselect in your main. js file to have access to the component. You also need to install it in your node_modules directory by running npm install vue-multiselect --save first.


1 Answers

Change your function module to properly use ES6 export:

export function randomId() { /*My function ...*/ }

And then use ES6 named import:

import { randomId } from '../functions/randomId';
like image 119
connexo Avatar answered Nov 14 '22 22:11

connexo