[英]Vue.js Data binding issue
我正在嘗試通過發布請求在我的 userDetails 數組中綁定數據,但我沒有得到數據,我已經嘗試了 stackoverflow 和 vue.js 文檔中給出的所有可能的解決方案,但我的代碼對我沒有任何幫助。
ND.user_list = new Vue({
el: '#user_list',
data: {
userDetails: []
},
mounted: function () {
$.post(ND.routes['users.get'], [], function(data) {
//console,log(data);
this.$set(this, 'userDetails', data);
//this.usersDetails = data;
}.bind(this), 'json');
//onsole.log(this.userDetailsdata);
}
});
我在安裝函數的控制台登錄中獲取數據,但沒有進入數據中聲明的 userDetails 數組。 這是我的查看代碼
<div class="ui grid container" id="user_list">
<table class="ui celled padded table">
<thead>
<tr>
<th colspan="6">Top Users</th>
</tr>
</thead>
<thead>
<tr>
<th class="ui center aligned">#</th>
<th class="ui center aligned">Name </th>
<th class="ui center aligned">Email </th>
<th class="ui center aligned">User Type</th>
<th class="ui center aligned">Action </th>
</tr>
</thead>
<tbody>
{% verbatim %}
<tr v-for="user in userDetails">
<td>1</td>
<td class="single line">{{ user.email }}</td>
<td class="ui center aligned "></td>
<td class="ui center aligned "></td>
<td class="ui center aligned ">
<select class="ui dropdown">
<option value=" ">Action </option>
<option value="1">Edit</option>
<option value="0">Delete</option>
</select>
</td>
</tr>
{% endverbatim %}
</tbody>
</table>
</div>
提前致謝。
$.post()
回調中的this
不引用 VueJS 實例。 這意味着this.userDetails
實際上會在回調中返回 undefined 。 您可以做的是為 VueJS 實例創建一個代理,如下所示:
ND.user_list = new Vue({
el: '#user_list',
data: {
userDetails: []
},
mounted: function () {
// Proxy `this`
var that = this;
$.post(ND.routes['users.get'], [], function(data) {
// `that` will refer to VueJS instance
that.userDetails = data;
}, 'json');
}
});
您使用 this.$set 錯誤:僅當您在數據對象中有一個對象並希望向該對象添加以前不存在的屬性時,或者如果您想更改數組的索引時,才應使用它。 那么第一個參數不應該是vue對象,而是數據對象(即數據對象中的對象或數組)。 請參閱此處的文檔: https ://v2.vuejs.org/v2/guide/reactivity.html 或https://v2.vuejs.org/v2/api/#Vue-set 。
而不是: this.$set(this, 'userDetails', data);
你應該這樣做this.userDetails = data;
. 你試過這個嗎? 另外,如果你改變了數組中的元素,那么你應該使用 Vue.set 或 splice,但在使用之前請仔細閱讀文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.