TypeError: Cannot set properties of undefined (setting ‘xx‘)
目录
问题描述
我在编写axios请求后端数据的时候,一直出现下面的错误前端页面显示不出来。
报错:
TypeError: Cannot set properties of undefined (setting ‘xx’)
原因分析:
this指向的对象发生了变化(现在this代表axios对象),需要在函数前将this指向的对象提前保存一下
解决方案:
方法一:回调函数使用箭头函数来使用。(responde)=>{}
<template>
<el-table :data="tableData" style="width: 100%" stripe>
<el-table-column prop="name" label="姓名" width="250" />
<el-table-column prop="age" label="年龄" width="250" />
<el-table-column prop="gender" label="性别" width="250" />
<el-table-column prop="createTime" label="创建时间" width="250" />
<el-table-column fixed="right" label="操作" width="250">
<template #default>
<el-button link type="primary" size="small">编辑</el-button>
<el-button link type="primary" size="small">删除</el-button>
</template>
</el-table-column>
</el-table>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
tableData:[]
}
},
created(){//为何 要在created 方法中 发请求,因为该方法 可以操作tableData属性
// 解决方法一
axios.get('http://localhost:9090/student') // url 请求后台的地址
/*
* .then(function (response) 这样写前端会报错
* 报错信息:TypeError: Cannot set properties of undefined (setting 'tableData')at eval (Student.vue?401d:59:1)
* 这样写是匿名函数,无法取到tableData的值,所以tableData的值为undefined,不能给undefined的变量赋值
* 解决办法:1.改为箭头函数 2.将this重新赋值给新的变量
*/
// .then(function (response) { //成功回调方法(访问后台成功,后台有数据返回,则进入该方法)
.then(response=> { //成功回调方法(访问后台成功,后台有数据返回,则进入该方法)
console.log(response);
console.log(response.data)
this.tableData = response.data;
})
.catch(function (error) {//失败回调方法(访问后台失败,返回失败的信息,则进入该方法)
console.log(error);
});
},
methods:{
}
}
</script>
方法二:暂存this。var th = this; 在内部用th.xx代替this.xx
//解决办法二
var th = this;
axios.get('http://localhost:9090/student') // url 请求后台的地址
.then(function (response) { //成功回调方法(访问后台成功,后台有数据返回,则进入该方法)
console.log(response);
console.log(response.data)
th.tableData = response.data;
})
.catch(function (error) {//失败回调方法(访问后台失败,返回失败的信息,则进入该方法)
console.log(error);
});
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/85580.html