gpt4 book ai didi

javascript - Vue中没有定义axios

转载 作者:搜寻专家 更新时间:2023-10-30 22:30:08 25 4
gpt4 key购买 nike

我正在尝试从 Wordpress API 获取数据。我的控制台向我抛出错误“axios 未定义”。这是我的 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 install 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')

谁能帮我解决这个问题?我不明白我哪里错了?

谢谢大家

最佳答案

您需要将 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

这是有益的,因为:

  • 当您需要更改基本 URL 时,您不必更改 30 个地方。
  • 您不必在 axios 调用中反复添加相同的 header 。
  • 您可以像这样在通话中使用更短的 url:

    API.get('foo/bar/')
    .then(响应=> {
    }

关于javascript - Vue中没有定义axios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53093902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com