0

我试图使用 vuejs 作为 WP restapi 的前端脚手架。我需要所有 vue 组件都可以访问由 wordpress 生成的 api url。这是我所做的:

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

问题是,我可以从模板标签内部访问变量,如下所示:

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

但是我无法在组件的方法中访问它:

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);
    });
  }
}

在这部分代码中,它给了我这个错误:

ReferenceError: apiURL is not defined

什么是正确的方法。我正在使用 VueJS 版本 2。

4

1 回答 1

1

TLDR:使用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>


全局 mixinapiURL为所有 Vue 实例添加了一个数据字段 ( ),您可以像在组件中本地声明的任何其他数据字段一样访问该字段(即,在您的情况下使用this.FIELDNAME,因此this.apiURL)。否则,如果没有this关键字,访问apiURL指的是一些window未定义的全局变量 (of )。

于 2018-04-02T06:02:16.423 回答