1

I am using asiox/vuejs to create a webpage. However I want to compartmentalize the code more. One example is I use axios to make requests to the backend, and the data in the response is commited into vuex.

this.$axios.get('events').then((response) => {
  this.$store.commit('data/populate', response.data)
})
.catch((e) => {
  console.error(e)
})

I want to write a util method for this, like this.$populate.events()

I have tried creating utils inside the plugins/ directory, but they dont have access to this.$axios or this.$store

Note that I have axios and vuex imported in nuxt.config.js

How can this be achieved?

2 Answers 2

1

If you need the function in the context, Vue instances and maybe even in the Vuex store, you can use the inject function, which is the second parameter of the plugins exported function.

Injecting content into Vue instances works similar to when doing this in standard Vue apps. The $ will be prepended automatically to the function.

Reference

export default ({ app, store }, inject) => {
  inject("populate", () => {
    app.$axios
      .get("events")
      .then(response => {
        store.commit("data/populate", response.data);
      })
      .catch(e => {
        console.error(e);
      });
  });
};

app variable is context property.

The root Vue instance options that includes all your plugins. For example, when using axios, you can get access to $axios through context.app.$axios.

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

Comments

0

Figured it out not 5 minutes after posting ...

Basically use this nuxt guide

And replace this with app in the method you'd like to move

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.