8

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 3

13

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

Sign up to request clarification or add additional context in comments.

1 Comment

You could also simply move the method outside of the Vue component (just above it) and call it as a normal JS function, if it doesn't need access to the component at all.
1

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>

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.