如何在选择框中使用Vue循环使类别和子类别选项看起来像这样:
+新闻
-运动
-国际
+ blog
我可以使用PHP来做到这一点:
@foreach($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
@foreach($category->subcategory as $sub)
<option value="{{$sub->id}}">-{{$sub->name}}</option>
@endforeach
@endforeach
**我想在Vue组件中使用它**
答案 0 :(得分:1)
在vuejs中创建嵌套选择器非常简单
// Initialize the vue instance
var app = new Vue({
el: '#app',
// Initialize the data, in the case that you are using Laravel
//and Blade for example here is where you will need to retrive
//all the categories like:
// data: {{ Category::with(['subcategories'])->get() }}
data: {
categorySelected: null,
subcategorySelected: null,
message: 'Hello Vue!',
categories: [
{
name: 'news',
subcategories: [
{
name: 'sport'
},
{
name: 'international'
}
]
},
{
name: 'blog',
subcategories: [
{
name: 'a blog subcategpry example'
},
{
name: 'another blog subcategpry example'
}
]
}
]
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<label>Category Selectded : {{ categorySelected ? categorySelected.name : null }}</label> <br>
<label>Subcategory Selectded : {{ subcategorySelected ? subcategorySelected.name : null }}</label> <br>
<select v-model="categorySelected">
<optgroup v-for="category in categories" :label="category.name">
<option
v-for="subcategory in category.subcategories"
:value="subcategory"
>
{{subcategory.name}}
</option>
</optgroup>
</select>
<div>
答案 1 :(得分:0)
您可以在optgroup中使用,例如:
<select v-model="selectedcategory" name="parent" class="form-control">
<optgroup v-for="category in categories">
<option :value="category.id">+{{category.name}}</option>
<option v-for="subcategory in category.subcategories" :value="subcategory.id">
-{{subcategory.name}}
</option>
</optgroup>
答案 2 :(得分:-2)
尝试一下。 Js:
let vm = new Vue({
el: "#app",
data: {
integer: [{
id: 1,
name: 'odd',
numbers: [{id: 1, name: 'one'}, {id: 3, name: 'three'}]
}, {
id: 2,
name: 'even',
numbers: [{id: 2, name: 'two'}, {id: 4, name: 'four'}]
}],
},
});
HTML:
<option v-for="item in integer" :value="item.id" v-text="item.name"></option>
<option v-for="num in item.numbers" :value="num.id" v-text="num.name"></option>