简体   繁体   English

如何在Vue select中使用foreach?

[英]How can I use foreach in a Vue select?

How can I use a Vue loop in a select box to make category and subcategory options look like this : 如何在选择框中使用Vue循环使类别和子类别选项如下所示:

+news +新闻
-sport -运动
-international -国际
+blog +博客

I can do it with PHP like this: 我可以用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 

** I want to use this in a Vue component ** **我想在Vue组件中使用它**

To its very simple to make a nesteed selector in vuejs 在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> 

Try this. 尝试这个。 Js: 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: 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM