我正在尝试从Wordpress API中获取数据。我的控制台向我抛出错误“未定义轴”。 这是我的post.vue组件。
<template>
<div>
<table class="table is-bordered">
<thead>
<tr>
<th>Title</th>
<th>Posted at</th>
</tr>
</thead>
<tbody>
<tr v-for="post in posts" :key="post.id">
<td>{{post.title.rendered}}</td>
<td>{{post.date_gmt}}</td>
</tr>
</tbody>
</table>
<pagination :pagination="pagination"
@prev="--postsData.page; getPosts();"
@next="postsData.page++; getPosts();">
</pagination>
</div>
</template>
<script>
import pagination from './pagination.vue'
export default {
mounted() {
this.getPosts();
},
components: {
'pagination': pagination
},
data() {
return {
postsUrl: 'http://localhost:8080/wp-json/wp/v2/posts',
posts: [],
postsData: {
per_page: 10,
page: 1
},
pagination: {
prevPage: '',
nextPage: '',
totalPages: '',
from: '',
to: '',
total: '',
},
}
},
methods: {
getPosts() {
axios
.get(this.postsUrl, {params: this.postsData})
.then((response) => {
this.posts = response;
this.configPagination(response.headers);
})
.catch( (error) => {
console.log(error);
});
},
configPagination(headers) {
this.pagination.total = +headers['x-wp-total'];
this.pagination.totalPages = +headers['x-wp-totalpages'];
this.pagination.from = this.pagination.total ? ((this.postsData.page - 1) * this.postsData.per_page) + 1 : ' ';
this.pagination.to = (this.postsData.page * this.postsData.per_page) > this.pagination.total ? this.pagination.total : this.postsData.page * this.postsData.per_page;
this.pagination.prevPage = this.postsData.page > 1 ? this.postsData.page : '';
this.pagination.nextPage = this.postsData.page < this.pagination.totalPages ? this.postsData.page + 1 : '';
}
}
}
</script>
我真的不知道这里出了什么问题,我安装了axios,npm安装了axios,
这是我的main.js文件
import Vue from 'vue'
import App from './App.vue'
import posts from "./components/posts.vue";
import axios from "axios";
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
Vue.prototype.$axios = axios;
Vue.component('posts', posts);
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
有人可以帮助我吗?我看不到哪里错了?
谢谢大家
答案 0 :(得分:5)
您需要将import axios from 'axios'
添加到组件中。最好在您的src目录中创建一个名为api.js的配置文件,并添加如下内容:
import axios from 'axios';
export default axios.create({
baseURL: `http://127.0.0.1:8000/`,
headers: {
'Content-Type': 'application/json',
'Authorization': "JWT " + localStorage.getItem('token')
},
xsrfCookieName: 'csrftoken',
xsrfHeaderName: 'X-CSRFToken',
withCredentials: true
});
然后在导入的组件中像这样:
import API from '../api'
执行API.get而不是axios.get
这是有益的,因为:
您可以在通话中使用较短的网址,例如:
API.get('foo/bar/')
.then(response => {
}