0

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.

1 Answer 1

1

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/[email protected]"></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.

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

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.