laravel vue控件通过axios向api发起请求,获取分页实例对象reponse.data.data

本文介绍如何在Vue项目中使用Axios发起HTTP请求并解析分页数据。通过注册Axios到Vue原型,可以方便地进行POST请求。文章详细解释了为什么需要两次访问'data'属性来获取Laravel返回的分页数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:在vue中获取分页实例对象中的具体实例对象的时候需要使用reponse.data.data,为什么需要调用两次data呢?请看下文


一、什么是Axios

axios文档链接

在文档中我们可知,Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

其拥有如下特点:

  • 从浏览器中创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求数据和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防御 XSRF
二、在vue中发起请求

首先需要在应用vue的页面中注册axios,比如注册到页面引入的js文件中,注册代码如下:

Vue.prototype.$http = window.axios;

然后就可以在vue中发起请求了:

window.axios.post('api_url').then(function(response){
	console.log(reponse);
      }

三、api返回数据

$users = User::orderBy('id')->paginate(5);
return $users;
四、处理响应的数据

axios对响应的数据的处理,写在.then方法的闭包函数内,如上文中我们将返回的数据打印输出在控制台。

控制台打印如下:


首先,我们得知这是一个object对象

然后我们将其展开来看:


也就是说,reponse是以json形式返回的,其中包括了响应的各种属性:配置、数据内容(data)、响应头、请求体、响应状态码、响应结果文本、__proto__。

细看data(第一层data)这一个属性,我们可以得知此时其中装了一个obejct


观察发现是我们api返回的分页对象实例。

Laravel文档中提到,”the paginator instances are iterators and may be looped as an array“,也就是说,分页实例对象本身是可以直接参与循环,直接在blade中输出详细内容。

但是此时我们在vue中,需要将具体内容取出来,赋值给变量而非直接渲染输出,就需要准确逐层取值。

paginate实例对象,其属性包含:

{
   "total": ,
   "per_page": ,
   "current_page": ,
   "last_page": ,
   "first_page_url": "",
   "last_page_url": "",
   "next_page_url": "",
   "prev_page_url": null,
   "path": "",
   "from": ,
   "to": ,
   "data":[
        {
            // Result Object
        },
        {
            // Result Object
        }
   ]
}

因为data属性里面装的是对象数组,我们要获取返回的user对象的数据,就需要取其的data属性( 第二层data):

vm.users = response.data.data;






<template> <div class="login-container"> <div class="login-form"> <h2>用户登录</h2> <input v-model="username" placeholder="用户名"> <input v-model="password" type="password" placeholder="密码"> <button @click="handleLogin">登录</button> <!-- <router-link to="/register">注册账号</router-link> --> </div> </div> </template> <script setup> import { ref } from 'vue' import { useRouter } from 'vue-router' import axios from 'axios' import { ElMessage } from 'element-plus' const router = useRouter() const username = ref('') const password = ref('') const handleLogin = async () => { try { // 发送POST请求到登录接口 const response = await axios.post('http://172.26.26.43/dev-api/login', { username: username.value, password: password.value }) const { code, message, token } = response.data // 根据状态码判断登录是否成功 if (code === 200) { // 存储token到localStorage localStorage.setItem('token', token) ElMessage.success({ message:'登录成功!', customClass:'mobile-message', duration: 1000 }) setTimeout(() => { // 登录成功后跳转到详情页 router.push({ name: 'Detail' , params: { id: 123 } }) }, 1000) } else { alert(`登录失败: ${message}`) } } catch (error) { // 处理请求错误 console.error('登录请求出错:', error) alert('登录请求失败,请检查网络或联系管理员') } } </script> <style scoped> /* 添加移动端适配的样式 */ .login-container { display: flex; justify-content: center; align-items: center; min-height: 100vh; /* 使容器至少和视口一样高 */ background-color: #f5f5f5; /* 背景色 */ padding: 16px; /* 内边距 */ } .login-form { width: 100%; max-width: 400px; /* 最大宽度,避免在大屏幕上过宽 */ padding: 20px; background: #fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); } .login-form h2 { text-align: center; margin-bottom: 20px; color: #333; } .login-form input { width: 100%; padding: 12px; margin-bottom: 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 16px; box-sizing: border-box; /* 确保宽度包含内边距和边框 */ } .login-form button { width: 100%; padding: 12px; background-color: #007bff; color: white; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; } /* 按钮的点击区域已经足够大(高度44px左右) */ .login-form button:active { background-color: #0056b3; } .login-form a { display: block; text-align: center; margin-top: 12px; color: #007bff; text-decoration: none; } </style> 这个是我的登录界面,我在登录成功后获取到接口返回的token,在详情页面会用到这个token,详情界面代码:<template> <div class="detail-container"> <!-- 索引板块卡片 --> <el-card class="index-card"> <!-- 表单区域 --> <el-form :model="formData" label-position="top" ref="indexForm" class="mobile-form" > <!-- 问卷标题 --> <el-form-item label="问卷标题:" prop="dcWjTitle"> <el-input v-model="formData.dcWjTitle" placeholder="请输入问卷标题" clearable :prefix-icon="Document" /> </el-form-item> <!-- 被测评人 --> <el-form-item label="被测评人:" prop="dcId"> <el-input v-model="formData.dcId" placeholder="请输入被测评人ID" clearable :prefix-icon="User" /> </el-form-item> <!-- 人员部门 --> <el-form-item label="人员部门:" prop="dcDept"> <el-input v-model="formData.dcDept" placeholder="请输入人员部门" clearable :prefix-icon="OfficeBuilding" /> </el-form-item> <!-- 提交状态 --> <el-form-item label="提交状态:" prop="state"> <el-select v-model="formData.state" placeholder="请选择提交状态" clearable class="mobile-select" > <el-option label="已提交" :value="1" /> <el-option label="未提交" :value="0" /> </el-select> </el-form-item> <!-- 新增:按钮区域 --> <el-form-item class="button-group"> <el-button type="primary" @click="handleSearch" class="action-button" :icon="Search" > 搜索 </el-button> <el-button @click="handleReset" class="action-button" :icon="Refresh" > 重置 </el-button> </el-form-item> </el-form> </el-card> <!-- 数据显示板块 --> <el-card class="data-card"> <template #header> <div class="card-header"> <span>测评数据列表</span> <el-button type="primary" size="small" :icon="Refresh" @click="fetchData" > 刷新数据 </el-button> </div> </template> <!-- 数据表格 --> <el-table :data="tableData" v-loading="loading" element-loading-text="数据加载中..." stripe style="width: 100%" class="mobile-table" > <el-table-column prop="id" label="ID" width="80" /> <el-table-column prop="dcWjTitle" label="问卷标题" min-width="150" /> <el-table-column prop="dcId" label="被测评人ID" width="120" /> <el-table-column prop="dcDept" label="部门" width="120" /> <el-table-column prop="state" label="提交状态" width="100"> <template #default="scope"> <el-tag :type="scope.row.state === 1 ? 'success' : 'info'"> {{ scope.row.state === 1 ? '已提交' : '未提交' }} </el-tag> </template> </el-table-column> <el-table-column prop="createTime" label="创建时间" width="180" /> <el-table-column label="操作" width="120" fixed="right"> <template #default="scope"> <el-button size="small" type="primary" @click="handleView(scope.row)" > 查看 </el-button> </template> </el-table-column> </el-table> <!-- 分页控件 --> <div class="pagination-container"> <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size" :page-sizes="[5, 10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" @size-change="handleSizeChange" @current-change="handlePageChange" /> </div> </el-card> </div> </template> <script setup> // 确保正确导入所有 Vue 函数 import { ref, reactive, onMounted, onUnmounted } from 'vue'; import axios from 'axios'; import { Document, User, OfficeBuilding, Search, Refresh } from '@element-plus/icons-vue'; import { ElMessage } from 'element-plus'; // 环境变量管理API地址 const API_BASE = import.meta.env.VITE_API_BASE || 'http://172.26.26.43/dev-api'; const API_URL = `${API_BASE}/wjdc/wj/listTx`; // 表单数据 const formData = reactive({ dcWjTitle: '', dcId: '', dcDept: '', state: null }); // 表格数据 const tableData = ref([]); const loading = ref(false); // 分页配置 const pagination = reactive({ current: 1, size: 10, total: 0 }); // 表单引用 const indexForm = ref(null); // 请求取消令牌 let cancelTokenSource = axios.CancelToken.source(); // 搜索按钮处理函数 - 添加防抖 let searchTimer = null; const handleSearch = () => { if (searchTimer) clearTimeout(searchTimer); searchTimer = setTimeout(() => { pagination.current = 1; fetchData(); }, 300); }; // 重置按钮处理函数 const handleReset = () => { if (indexForm.value) { indexForm.value.resetFields(); } handleSearch(); }; // 查看详情 const handleView = (row) => { console.log('查看详情:', row); // 这里可以实现查看详情的逻辑 }; // 分页大小改变 const handleSizeChange = (size) => { pagination.size = size; fetchData(); }; // 页码改变 const handlePageChange = (page) => { pagination.current = page; fetchData(); }; // 获取数据 const fetchData = async () => { // 取消之前的请求 if (cancelTokenSource) { cancelTokenSource.cancel('请求被取消'); } cancelTokenSource = axios.CancelToken.source(); loading.value = true; try { // 构造请求参数 const params = { pageNum: pagination.current, pageSize: pagination.size, ...formData }; // 调用API const response = await axios.get(API_URL, { params, cancelToken: cancelTokenSource.token, headers: { 'Content-Type': 'application/json' } }); // 处理响应数据 const { data } = response; if (data && data.code === 200) { tableData.value = data.data.rows || []; pagination.total = data.data.total || 0; // 空数据提示 if (tableData.value.length === 0) { ElMessage.info('没有找到匹配的数据'); } } else { const errorMsg = data?.msg || '未知错误'; console.error('API返回错误:', errorMsg); ElMessage.error(`请求失败: ${errorMsg}`); tableData.value = []; pagination.total = 0; } } catch (error) { // 忽略取消请求的错误 if (!axios.isCancel(error)) { console.error('获取数据失败:', error); ElMessage.error('网络请求失败,请稍后重试'); tableData.value = []; pagination.total = 0; } } finally { loading.value = false; } }; // 页面加载时获取初始数据 onMounted(() => { fetchData(); }); // 组件卸载时取消所有请求 onUnmounted(() => { if (cancelTokenSource) { cancelTokenSource.cancel('组件卸载,取消请求'); } }); </script> <style scoped> /* 移动端适配样式 */ .detail-container { padding: 12px; } .index-card { border-radius: 12px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); } .card-header { font-size: 18px; font-weight: 600; color: #1a1a1a; } .mobile-form { :deep(.el-form-item__label) { font-weight: 500; margin-bottom: 6px; } :deep(.el-input__inner) { height: 44px; border-radius: 8px; } } .mobile-select { width: 100%; :deep(.el-input__inner) { height: 44px; } } /* 按钮区域样式 */ .button-group { display: flex; gap: 12px; margin-top: 16px; } .action-button { flex: 1; height: 46px; font-size: 16px; border-radius: 8px; } /* 移动端响应式调整 */ @media (max-width: 480px) { .button-group { flex-direction: column; gap: 10px; } .action-button { width: 100%; } } </style>
最新发布
07-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值