vue2+ 动态更新文件定义的变量值(前后端交互)
问题:Cannot read property ‘message1’ of undefined"
TypeError: Cannot set property ‘studqllist’ of undefined
解决方法+:(1)方法开始时定义文件对象实例this==》
let $selfthis = this
.then(function (response) {
if (response.data != null) {
$selfthis.message1 = '查询返回1。。。'
let jsonD = response.data // JSON.parse(response.data);
$selfthis.studqllist = jsonD
}
})
(2)或者使用 箭头函数 “=>"
.then(response => {
if (response.data != null) {
this.message1 = '查询返回=>。。。'
let jsonD = response.data // JSON.parse(response.data);
this.studqllist = jsonD
}
})
```javascript
**点评:**关键还是 this 对象实例问题
在方法中this指当前文件export对象实例;
在方法(函数)F1内部的函数F2,this指函数对象本身(调用它的对象F1)。
这边是需要代表整个对象实例==》export对象。
**完整的studentListnew.vue代码,如下**
```javascript
<template>
<div>
<a
href="http://localhost:8085/listStudent"
target="_blank"
> listStudent
</a><br>
<input v-model="qlrmc" id="qlrmc">
<!-- `query` 是在下面定义的方法名 -->
<button v-on:click="query">查询</button>
<table>
<tr>
<td>show_qlrmc</td>
<td>bdcdyh</td>
</tr>
<tr v-for="item in studqllist" v-bind:key="item">
<td>{{item.show_qlrmc}}</td>
<td>{{item.bdcdyh}}</td>
</tr>
</table>
<label>{{message1}}</label>
</div>
</template>
<script>
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$axios = axios
// 【跨域问题】开发环境,使用webpack提供的http代理服务器进行访问真实的网络服务器url (./config=>index.js==> proxyTable:)
axios.defaults.baseURL = '/v2api'
axios.defaults.headers.post['Content-Type'] = 'application/json'
// let message1 = '111' //这边可以不用定义,如果没有默认值的话,直接data里面初始化即可
export default {
name: 'studentList',
data () {
return {
/**
* 路由地址
*/
url: '/listStudentByName',
studqllist: [],
message1: '测试前后台交互',
qlrmc: ''
}
},
computed: {
},
methods: {
query: function () {
let $selfthis = this
// let strqlrmc = $("#qlrmc").val()
axios.post(this.url, {
show_qlrmc: $selfthis.qlrmc
}
// // let $selfthis = this 和 => 箭头函数的方式都可以正常绑定 20210201
// ).then(function (response) {
// if (response.data != null) {
// $selfthis.message1 = '查询返回1。。。'
// let jsonD = response.data // JSON.parse(response.data);
// $selfthis.studqllist = jsonD
// }
// }
).then(response => {
if (response.data != null) {
$selfthis.message1 = '查询返回=>。。。'
let jsonD = response.data // JSON.parse(response.data);
$selfthis.studqllist = jsonD
}
}).catch(function (error) {
console.log(error)
})// end axios.then
}
}
}
</script>
<style scoped>
</style>
刚开始学,是最容易遇见问题和解决问题的时候,越是最容易纠结和释怀的时候,希望本文对初入学者有一点点的帮助!【语来了】