Access component methods from asyncData - nuxtjs

Viewed 9424

I'm using nuxtjs, and I'm trying to figure out if it is possible to access component methods from the async data function.

For example I want to do something like this:

methods: {
    parseResult(data) {
        // do somthing with data...
    }
},

async asyncData({ app }) {
    const { data } = await app.$axios.get('/some/api')
    return app.parseResult(data)
},
3 Answers

You can't. It's stated in docs

You do NOT have access of the component instance through this inside asyncData because it is called before initiating the component.

You could move your method into vuex store and call it from asyncdata

As pointed out by fredrivett in the comments, you can move your parse function outside the export default area in order to use it inside asyncData, as a normal js function:

<script>

let parseResult = (data) => {
        // do somthing with data...
    }

export default {
  async asyncData({ app }) {
    const { data } = await app.$axios.get('/some/api')
    return parseResult(data)
  },
}

</script>

I normaly change asyncData() to fetch() and it works.

Related