Vue - Access Mixin Data from Mixin Method

Viewed 42

I have following piece of code and cannot seem to access the mixin data/variable loading from mixin method. What am I doing wrong here?

Vue.mixin({
    data: function () {
        return {
            loading: false,
        };
    },
    methods: {
        getEntityList: async (entityName) => {
            loading = true 
            return await axios
                .get("/api/" + entityName)
                .then((response) => {
                    loading = false;
                    return response.data;
                });
        },
    },
});

In Vue component, I am calling this function like:

export default {
  name: "somename",
  data() {
    return {
      accounts: [],
    };
  },

  mounted() {
    this.getEntityList('account').then(e => this.accounts = e);
  },
};
3 Answers

in condition you are using the options API, you need to reference your loading oh yes, vue has a behavior where you need to use "this.function" to declare your functions etc.. with a this.

this.loading = true and this.loading = false

A tip, to help! In the browser console, you can put the name of the Vue instance, in your case it is > Vue.mixin. One more thing you didn't instantiate anything like below. For example:

var app = new Vue({
            el: "#app",
            data: {

ok or try something like this.

data: {
  loading: false,
  methods:{
  loadingFunction: function () {
    this.loading = false;
    // or return this.loading
  }
 }
}

loading should be this.loading, as another answer shows. Otherwise it accesses global variable that doesn't exist and isn't specific to a component, also not reactive.

getEntityList is arrow function. The choice between regular and arrow function should always be justified. Here an arrow will prevent from using correct this context.

then doesn't need to be used together with async..await, the latter is supposed to replace it.

It should be:

    async getEntityList(entityName) {
        this.loading = true 
        let response = await axios
            .get("/api/" + entityName);
        this.loading = false;
        return response.data;
    },
Related