Home > front end >  Get function inside default export function
Get function inside default export function

Time:05-07

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

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

then I import it to index.js

import userService from './user';

export default ({ app }, inject) => {     
  inject('userService', userService);
  ...other service....
}

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related