答案 0 :(得分:2)
您需要在相应的selected
上设置<option>
属性,并遵守Vue的one-way data flow范例。
您甚至可以通过停用<select>
来添加一些额外的可用性糖,直到post
和categories
都被加载...
<select class="form-control"
:disabled="!(post.category_id && categories.length)"
@input="setCategoryId($event.target.value)">
<option v-for="cat in categories"
:value="cat.id"
:selected="cat.id == post.category_id">
{{cat.name}}
</option>
</select>
和
methods: {
setCategoryId(categoryId) {
this.$emit('input', parseInt(categoryId))
}
}
然后,在包含上述实例/组件的Vue实例/组件中,只需使用
<post-form :post="post" :url="url"
v-model="post.category_id"></post-form>
有关详细信息,请参阅Components - Form Input Components using Custom Events。
JSFiddle demo~ https://jsfiddle.net/1oqjojjx/267/
仅供参考,我还要将categories
初始化为数组,而不是对象......
data () {
return {
categories: []
}
}
答案 1 :(得分:2)
您应该可以执行以下操作:
methods: {
syncCats: function() {
this.$http.get("/api/categories")
.then(function(res) {
this.categories = res.data
if(!this.post.category_id) {
this.post.category_id = this.categories[0].id
}
})
}
},