'Get function inside default export function

I have function inside user.js with default export like this

export default {  
  var getListFriends = async (accessToken) =>{
  }
  ....other function
  return {
    getListFriends,
    ...other function...
  }
}

then I import it to index.js

import userService from './user';

Then I will add only index.js to plugin.

I can call this.$userService (it shows as anonymous function) but this.$userService.getListFriends return undefined.

How can I call function getListFriends from import. Thank you very much.



Solution 1:[1]

where is user.js? if its inside plugins directory, you have to use inject to add it to your nuxt.

then you can access it via nuxt object inside your code. see this example from nuxt docs:

export default ({ app }, inject) => {
  // Inject $hello(msg) in Vue, context and store.
  inject('hello', msg => console.log(`Hello ${msg}!`))
}

you can see the full document here

Solution 2:[2]

ok now for this to work the way you want you need to change your user.js file,

export default {
  friends: () => {
    console.log('hi bro');
  },
  notFriends: () => {
    console.log('go away man im not your bro');
  }
};

something like this. you dont need inject or app in your user.js. and your code problem is that you are defining a function and trying to access it's inner values from the outside like:

function boo() {
  var b = 0;
}

you can not access the value of b with boo.b. its a local variable to the boo function

instead create a object and have multiple functions inside your object

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mamdasan
Solution 2 Mamdasan