wordpressvue.jsvuejs2vue-mixin

VueJS Global Mixin readonly variable not accessible from method in a component


I was trying to use vuejs as a frontend scaffolding with WP restapi. I needed the api url generated by wordpress accessible to all the vue components. Here is what I did:

Vue.mixin({
  data: function () {
    return {
      get apiURL () {
        return document.querySelector('link[rel="https://api.w.org/"]').href;
      }
    }
  }
});

The problem is that, I can access the variable is accessible from inside the template tag, like this:

<template>
    <div class="container">
        <p>{{ apiURL }}</p>
    </div>
</template>

But I can't access it inside a method from the component:

methods: {
  loadPosts: function () {
    this.status = 'Loading...';
    axios.get( apiURL + 'wp/v2/posts').then((response) => {
      this.status = '';
      this.posts = response.data;
      console.log(response.data);
    }).catch((error) => {
      console.log(error);
    });
  }
}

In this part of the code, it gives me this error:

ReferenceError: apiURL is not defined

What is the right way to do it. I am using VueJS version 2.


Solution

  • TLDR: Use this.apiURL:

    methods: {
      loadPosts: function () {
        axios.get( this.apiURL + 'wp/v2/posts').then((response) => {
          ...
        });
      }
    }
    

    Vue.mixin({
      data: function () {
        return {
          get apiURL () {
            return 'https://jsonplaceholder.typicode.com/';
          }
        }
      }
    });
    
    new Vue({
      el: '#app',
      methods: {
        loadPosts: function () {
          console.log(`loadPosts: ${this.apiURL}`);
        }
      }
    })
    <script src="https://unpkg.com/vue@2.5.13"></script>
    
    <div id="app">
      <button @click="loadPosts">loadPosts()</button>
    </div>


    The global mixin adds a data field (apiURL) to all Vue instances, and you would access that field as any other data field declared locally in the component (i.e., using this.FIELDNAME, so this.apiURL in your case). Otherwise without the this keyword, accessing apiURL refers to some global variable (of window), which isn't necessarily defined.