I have multiple functions in my vue component like this. Is there any way i can shift functions in some other file and then import those here . This is my App.vue
getLocation: async function () {
},
subscribe: function (longitude, latitude) {
},
async openLocationWarning() {
},
uploadData(data, key) {
},
downloadData()
{
}
No you cant but you can use mixins. You can also store it in a js file and export it.
export yourFunction() {
}
export anotherFunction(){
}
And import it in your file
import {yourFunction, anotherFunction} from 'path/to/your_file';
methods: {
callSomeFunction() {
// you can call it like this.
yourFunction();
}
}
Related
Back in my day we had this crazy thing called include or import or whatever. It meant that you wrote some code in one file and then reused it in different files. So you would create a class in file x, include this file in another file y and instantiate an object from this. Basically this means, that you were able to call a function form file y even though it is written in file x.
How can something like this be done in vue.js? I understand that the new hip way to do it is called "components api". Online I only found really convoluted examples that had some coupling with the dom, something I don't need.
Or should I use mixins? Mixins seem to be working at least, but they have a scope problem.
Here is the file I want to share (x.vue):
<script>
export default
{
data ()
{
return {
a: 'test'
}
}
,mounted ()
{
}
,methods:
{
test ()
{
console.log( "test : " + this.a );
}
}
}
</script>
The y.vue:
<script>
import x from './x.vue'
export default {
name:"whatever"
,components:
{
x
}
,mounted()
{
x.a = "it is working";
x.test();
}
}
</script>
The web-browser tells me that a is not a function. does anyone know where the mistake is? Or should i just create a js class and try to import that?
Thanks for any help.
I believe you're looking for mixins:
https://v2.vuejs.org/v2/guide/mixins.html
They Allow you to share functions, data, hooks and all other from another file.
This would be an approach in your case.
mixins.js:
export default {
methods: {
sayHello () {
console.log( "test : " + this.a);
}
}
};
component.vue:
<script>
import mixins from "#/path/to/mixins/mixins";
export default {
name: "whatever",
mixins: [mixins],
data ()
{
return {
a: 'HELLO'
}
},
created() {
this.sayHello();
}
}
</script>
For further information: Mixins
EDIT: Looks like there is something that matches your needs!
mixins.js:
export default {
name: 'Mixin',
methods: {
sayHello() {
console.log("Hello")
}
}
}
component.js:
export default {
name: 'whatever',
mixins: [Mixin],
created() {
this.$super(Mixin).sayHello();
}
}
EDIT2: As you requested, an simple example to pass arguments.
mixins.js:
export default {
methods: {
sayHello(foo, bar) {
console.log(foo + bar)
}
}
}
component.js:
export default {
name: 'whatever',
mixins: [Mixin],
data () {
return {
baz: 'Say'
}
},
created() {
this.sayHello(this.baz, " Hello");
}
}
Mixins are not useful in this case as there cannot be more than one instance of a mixin. It is like copy and pastes the code from the mixin into the other file.
Sharing code between Vue components can be done by many savers with standard js classes. All that is needed is that the class is declared with export default class.
I want to dynamically set the title of the window for each route, so in each routes: [] child object I have a meta: { title: ... } object. For example:
routes: [
{
path: 'profile/:id',
name: 'Profile',
component: Profile,
meta: {
title: function (to, cb) {
const profileId = parseInt(to.params.id);
// ... do stuff ...
}
}
}
]
I call this title function in an afterEach hook:
router.afterEach((to) => {
document.title = 'My Site';
if (to.meta && to.meta.title) {
to.meta.title(router.app, to, (result) => { document.title += ' | ' + result; });
}
});
In the ... do stuff ... portion I want to call a method from my mixin GetAndStore.js called loadProfile(profileId). I added GetAndStore into the router's mixins, but loadProfile is not available (this.loadProfile is undefined). I loaded GetAndStore globally and tried again with the same results. I've tried every configuration I can think of for the past hour I've not found any way at all to access the methods from GetAndStore from within this setup.
Any ideas of what I'm missing or what I'd need to restructure in order to access mixin methods from within routes->element->meta->title ?
The issue is that...
Mixins are a flexible way to distribute reusable functionalities for Vue components
Vue-router is not a component, nor do you have access to the component loaded for the route.
What I would suggest is making loadProfile a named export from your GetAndStore mixin. Assuming your mixin is exported like
import axios from 'axios' // just an example
export default {
methods: {
loadProfile (profileId) {
return axios.get(...)
}
}
}
you can move your function out of the default export and name it...
export function loadProfile (profileId) {
return axios.get(...)
}
export default {
methods: {
loadProfile
}
}
then you can import just the loadProfile function in your route definitions...
import { loadProfile } from 'GetAndStore'
Of course, you could also import your mixin as it is and just use
import GetAndStore from 'GetAndStore'
// snip
GetAndStore.methods.loadProfile(to.params.id).then(...)
Maybe you can try do it on beforeRouteEnter inside Profile component. So there you can grab meta title and set title of page and there you will have access to mixin methods:
beforeRouteEnter (to, from, next) {
if (to.meta && to.meta.title) {
to.meta.title(router.app, to, (result) => { document.title += ' | ' + result; });
}
},
Docs: https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards
Within a Vue component, I am calling a function from a separate JS file. I then need to call a method in my component just after this first function is completed:
My .vue component:
import myFunction from '#/components/functions';
export default {
name: 'test',
components: {
myFunction,
},
created(){
if (....) {
myFunction.function1(myParam)
.then((response) => {
this.method2();
});
},
methods:{
method2(){
something;
},
}
};
My separate functions.js file:
export default {
function1(myParam) {
...
return true;
},
};
I tried several things such as the last one shown in my code which gives me a
.function1(...).then is not a function
I am sure it is not that complicated but can not find the correct syntax.
The function in your other file could return a Promise or it can except a callback from your view component. Also, if you set this equal to self/vm and then use vm.method2(), this is because in the then callback this is defined in scope of that function not the Vue component.
I'm creating a unit converter, and I want to put all of the conversion functions into their own file. Using ES6 export, is there any way to export all of the functions in the file with their default names using only one line? For example:
export default all;
The functions are all just in the file, not within an object.
No, there's no wildcard export (except when you're re-exporting everything from another module, but that's not what you're asking about).
Simply put export in front of each function declaration you want exported, e.g.
export function foo() {
// ...
}
export function bar() {
// ...
}
...or of course, if you're using function expressions:
export var foo = function() {
// ...
};
export let bar = () => {
// ...
};
export const baz = value => {
// ...
};
I think there are a lot of solutions to this. And as has been answered, there's no wildcard export. But, you can 'wildcard' the import. So, I much prefer the one putting export before each of the functions you want to expose from the file:
//myfile.js
export function fn1() {...}
export function fn2() {...}
and then import it like so:
import * as MyFn from './myfile.js'
Afterwards you could use it like so:
MyFn.fn1();
MyFn.fn2();
You can also use module.exports as follows:
function myFunction(arg) {
console.debug(arg);
}
function otherFunction(arg) {
console.error(arg);
}
module.exports = {
myFunction: myFunction,
otherFunction: otherFunction,
};
Then you can import it:
import {myFunction, otherFunction} from "./Functions.js";
In my use case, I do have three reusable functions in one file.
utils/reusables.js
export const a = () => {}
export const b = () => {}
export const c = () => {}
In order to point the root folder instead of individual file names, I created a file called index.js which will comprise of all the functions that are listed in individual files.
utils/index.js
export * from './reusables'
Now, when I want to use my a function, I will have to simply import it like this
import { a } from '../utils'
Rather than calling it from its individual files
import { a } from '../utils/reusables'
You could also export them at the bottom of your script.
function cube(x) {
return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
var graph = {
options: {
color:'white',
thickness:'2px'
},
draw: function() {
console.log('From graph draw function');
}
}
export { cube, foo, graph };
You can also aggregate submodules together in a parent module so that they are available to import from that module.
// In parentModule.js
export { myFunction, myVariable } from 'childModule1.js';
export { myClass } from 'childModule2.js';
// In top-level module
import { myFunction, myVariable, myClass } from 'parentModule.js'
For Node.js environment, what I did to export functions was this.
UserController.js
module.exports = {
signUp: () => {
return "user"
},
login: () => {
return "login"
}
}
UserRouter.js
const UserController = require('./UserController')
then login and signUp functions could be used inside UserRouter as UserController.signUp() and UserController.login()
I think there's a missing common solution, which is exporting in index.js file:
myModule/myFunctions.js
export const foo = () => { ... }
export const bar = () => { ... }
then in myModule/index.js
export * from "./myFunctions.js";
This way you can simply import and use it with:
import { foo, bar } from "myModule";
foo();
bar();
functions.js
function alpha(msj) {
console.log('In alpha: ' + msj);
}
function beta(msj) {
console.log('In beta: ' + msj);
}
module.exports = {
alpha,
beta
};
main.js
const functions = require('./functions');
functions.alpha('Hi');
functions.beta('Hello');
Run
node main.js
Output
In alpha: Hi
In beta: Hello
In case anyone still needs an answer to this in modern JavaScript:
const hello = () => "hello there"
const bye = () => "bye bye"
export default { hello, bye }
What I like to do is to export all functions within an object:
//File.js
export default {
testFunction1: function testFunction1(){
console.log("Hello World")
},
//a little bit cleaner
testFunction2: () => {
console.log("Nothing here")
}
}
Now you can access the functions with calling the key value of the object:
//differentFile.js
import file from 'File.js'
file.testFunction1()
//Hello World
file.testFunction2()
//Nothing here
Let say i created a basic modules with simple functions like helper.js
export function HelloChandu() {
//How to access navigator props from here.
}
export function HelloTester() {
HelloChandu();
}
Then I imported this module in my component as import * as Helper from './helper';
In some element I then called onpress={Helper.HelloTester.bind(this)} So by this now I can access this.props in HelloTester function but I can not access this.props in HelloChandu function.
Question : How can I access this.props from any function in my helper.js module ? Like if there are 10-20 functions , and i don't have to pass as parameters around.
Thank You
I am afraid that if you want to access this.props in one of your functions you will need to pass this explicitily or to bind all the functions to the current this before using them.
There are several ways to do so.
function HelloChandu() {
alert(this.props);
}
function HelloTester() {
HelloChandu.apply(this);
// HelloChandu.call(this);
// HelloChandu.bind(this)();
// this::HelloChandu(); // Experimental!
}
const obj = {
props: 'my props'
}
HelloTester.bind(obj)()
An alternative way would be to wrap all the functions in another function.
function helpers() {
const functions = {
HelloChandu: () => {
alert(this.props);
},
HelloTester: () => {
functions.HelloChandu();
}
};
return functions;
}
const obj = {
props: 'my props'
}
helpers.call(obj).HelloTester();
1.You can persist props to AsyncStorage, whenever you need, you can access this props.
2.Or if you are familiar with closure, you can do like this :
function Helper(ps) {
function test() {
console.log(ps.sex);
}
function test2() {
console.log(ps.name);
}
return {
test: test,
test2: test2,
}
}
var obj = Helper({name: 'abc', sex: 'male'});
obj.test();
obj.test2();
then you should export Helper, and import Helper from 'Helper.js'
export function HelloChandu(_this) {
//How to access navigator props from here.
}
export function HelloTester(_this) {
HelloChandu(_this);
}