0
votes

I wrote a function to get user info and import it in other places, how can I use it to get data? Can someone please help me?

export function userInfo () {
  let res
  this.$http({
    url: this.$http.adornUrl('/sys/user/info'),
    method: 'get',
    params: this.$http.adornParams()
  }).then(({data}) => {
    if (data && data.code === 0) {
      res = data
    }
  })
  return res
}

I use userInfo() and got error: Error in activated hook: "TypeError: Cannot read property '$http' of undefined"

import {userInfo} from './getUserInfo'
activated () {
      userInfo()
    }
1

1 Answers

0
votes

You should define your function as a mixin in order to use component's this inside the function and you can call it using this.userInfo():

export default {
  methods: {
    userInfo () {
      let res
      this.$http({
        url: this.$http.adornUrl('/sys/user/info'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        if (data && data.code === 0) {
          res = data
        }
      })
      return res
    }
  }
}

and then use it like this:

import userInfoMixin from './getUserInfo'

export default {
  // ...
  mixins: [userInfoMixin],
  // ...
  activated () {
      this.userInfo()
  }
}

OR you can call your function and bind this to it like this:

import {userInfo} from './getUserInfo'
// ...
  activated () {
      userInfo.call(this)
  }

If you have several such functions and wish to use them in several components then you should prefer the first solution.