V-用于在控制台上取回之后不显示记录
问题描述:
对于接收到的响应,我有init数组ArtificialInsemination [],但它没有显示或加载表中的记录。当我点击按钮时,它调用函数viewRecords并成功发送HTTP请求,但不加载到表中。V-用于在控制台上取回之后不显示记录
<div id="ArtificialInsemination" class="container">
<button v-on:click="viewRecords">View Record</button>
<table class="table table-striped">
<thead>
<tr>
<th>Cow Id</th>
<th>Bull Name</th>
<th>Semen Origin</th>
<th>Insemination Time</th>
<th>Pd Delivery Date</th>
</tr>
</thead>
<tbody>
<tr v-for ="artificialInseminationRecord in artificialInseminationRecords">
<td>{{ artificialInseminationRecord.cowId }}</td>
<td>{{ artificialInseminationRecord.bullUsedName }}</td>
<td>{{ artificialInseminationRecord.semenOrigin }}</td>
<td>{{ artificialInseminationRecord.inseminationTime }}</td>
<td>{{ artificialInseminationRecord.pdStatusDate }}</td>
</tr>
</tbody>
</table>
</div>
这是VUE
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
<script src="https://unpkg.com/[email protected]/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js"></script>
<script>
//class initialization
var ArtificialInsemination = new Vue({
el:'#ArtificialInsemination',
data: {
url:'http://localhost/dairyfarm/index.php',
artificialInseminationRecords: []
},
//invoke methods
methods: {
viewRecords:function() {
var data = new FormData()
data.append('function','viewRecords')
axios.post(this.url,data)
.then(function (response) {
this.artificialInseminationRecords = response.data.data
}).catch(function (error) {
})
},
created: function(){
this.viewRecords()
}
}
})
</script>
答
你有一个范围的问题,this
回调里面指的是回调不Vue的实例的执行上下文。你需要要么分配this
的东西回调外:
// assign this to self
var self = this;
axios.post(this.url,data)
.then(function (response) {
self.artificialInseminationRecords = response.data.data
}).catch(function (error) {
})
或者使用arrow function不建立自己的执行上下文:
axios.post(this.url,data)
.then(response => {
this.artificialInseminationRecords = response.data.data
}).catch(function (error) {
})
答
我们只需要如果您使用ES2015我推荐你使用箭头功能选项,添加绑定这样
viewRecords:function() {
var data = new FormData()
data.append('function','viewRecords')
axios.post(this.url,data)
.then(function (response) {
this.artificialInseminationRecords = response.data.data
}.bind(this)).catch(function (error) {
})
}
。它是为了防止你不得不在整个地方绑定'this',这可能有点冗长。 –