[英]Vue.js prepopulating data
我有一個帶有多個組合框的表單,並且組合框是從REST服務中填充的,但是我的問題是,工作模型是在組合框所需的任何數據之前加載的,因此組合框從未設置為適當的值。
僅當我在load dropdown回調中設置了load model時,我才能使它起作用,但這看起來很雜亂,並且如果下拉列表超過一個,則無法工作。
如何在Vue中解決這個問題?
這是劇本
var app = new Vue({
el: '#categoryEdit',
data: {
category: {},
categories: []
},
methods: {
getCategory: function(categoryId) {
const config = {
headers: {
'Authorization': 'Bearer ' + '@token'
}
};
axios.get('/api/categories/' + categoryId, config)
.then(function(response) {
app.category = response.data;
console.log(app.category);
})
.catch(function(error) {
alert(error);
console.log(error);
});
},
add: function() {
const config = {
headers: {
'Authorization': 'Bearer ' + '@token'
}
};
axios.post('/api/categories/save', app.author, config);
},
fetchCategories: function() {
var config = {
headers: {
'Authorization': 'Bearer ' + '@token'
}
}
axios.get('/api/categories/all', config)
.then(function(response) {
app.categories = response.data;
})
.catch(function(error) {
alert(error)
console.log(error);
});
}
},
mounted: function() {
this.fetchCategories();
this.getCategory('@ViewContext.RouteData.Values["id"]');
}
})
這是HTML
<div class="form-group">
<label class="col-md-3 control-label">Kategorija</label>
<div class="col-md-9">
<select class="form-control select2 select2-hidden-accessible" v-model="category.ParentCategoryId">
<option v-for="cat in categories" :value="cat.Id">
{{cat.Name}}
</option>
</select>
</div>
</div>
加載所有類別后,嘗試加載類別:
mounted: function() {
this.fetchCategories()
.then(() => {
this.getCategory('@ViewContext.RouteData.Values["id"]')
})
}
為此,請確保fetchCategories
返回promise:
fetchCategories: function() {
var config = {
headers: {
'Authorization': 'Bearer ' + '@token'
}
}
return axios.get('/api/categories/all', config)
.then(response => {
this.categories = response.data;
})
.catch(error => {
alert(error)
console.log(error);
});
}
另外,最好將所有數據綁定到this
對象,您不希望您的應用程序代碼知道如何命名Vue實例變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.