Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access component methods from asyncData - nuxtjs

Tags:

vuejs2

nuxt.js

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)
},
like image 945
Elon Salfati Avatar asked Aug 27 '18 17:08

Elon Salfati


2 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

like image 95
Aldarund Avatar answered Oct 01 '22 01:10

Aldarund


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>
like image 35
Kenny Aires Avatar answered Oct 01 '22 01:10

Kenny Aires