What is the method to implement foreach within a Vue select component?

Is there a way to utilize a Vue loop within a select box in order to achieve the following category and subcategory options layout:

+news
-sport
-international
+blog

In PHP, I can accomplish this like so:

@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 

** My goal is to implement this functionality in a Vue component **

Answer №1

Creating a nested selector in vuejs is a fairly simple process.

// To start, initialize the Vue instance
var app = new Vue({
  el: '#app',
  // Set up the data, for example if you are using Laravel and Blade, 
  //you will need to retrieve 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 subcategory example'
          },
          {
            name: 'another blog subcategory example'
          }
        ]
      }
    ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <label>Category Selected: {{ categorySelected ? categorySelected.name : null }}</label> <br>
  <label>Subcategory Selected: {{ 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>

Answer №2

Give this a shot. JS:

const vueModel = new Vue({
    el: "#app",
    data: {
        collection: [{
            id: 1,
            label: 'primary',
            items: [{id: 1, name: 'one'}, {id: 3, name: 'three'}]
        }, {
            id: 2,
            label: 'secondary',
            items: [{id: 2, name: 'two'}, {id: 4, name: 'four'}]
        }],
    },
});

HTML:

<option v-for="element in collection" :value="element.id" v-text="element.label"></option>
    <option v-for="numItem in element.items" :value="numItem.id" v-text="numItem.name"></option>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Invoking a JavaScript class using a script tag

In my code, I have a class declaration in a script that is imported before the body tag: $(document).ready(function(){ var FamilyTree = function() { }; FamilyTree.prototype.displayMessage=function() { alert("test"); } }); Then, within the bo ...

Several components utilizing a popup module

I have created a modal popup example where scrolling is disabled in the background but enabled within the pop-up itself. Check out my demo here: View Demo My challenge lies in implementing a grid of images on the website: Take a look at the type of grid ...

Retrieve files from Amazon S3 using JavaScript

I'm currently working with a javascript file that's intended to download a text file from one of my S3 buckets. However, after running this file using "node file.js", nothing happens and there's no output. Is there something I'm missing ...

Ways to detect the use of vue.js on a webpage without relying on vue-devtools

One way to determine if the page is utilizing Angular or AngularJS is by inspecting window.ng and window.angular. Is there a similar method to identify whether Vue is being used on the page directly from the console, without relying on vue-devtools? ...

What is the best way to align a <div> element below another without being on the same line?

I'm currently working on developing a snake game. My focus right now is figuring out how to make the body parts of the snake follow the head and be positioned after it. <!--Player--> <div class="snake"></div> So here we have the sn ...

How to filter jQuery DataTables by column using comparison operators

Recently, I've been utilizing the amazing DataTables jQuery plugin along with the filter plug in. But now, I find myself pondering if there's a way to filter table columns by row using a comparison operator (such as '<', '>', ...

JavaScript code for downloading data through AJAX and then loading a chart is not functioning as expected

<script> var highchartsOptions = { chart: { backgroundColor: 'rgba(255, 255, 255, 0.1)', type: 'column' }, title: { text: '' }, exporting: ...

Is there a way for me to extract and showcase the initial 10 items bearing a particular class name from a different html document on my homepage?

I am looking to extract a list of movies from an HTML file titled "movies.html". The structure of the file is as follows: <div class="movie">Content 1</div> <div class="movie">Content 2</div> <div class=" ...

Does the syntax for the $.ajax() function appear to be incorrect in this instance?

I am attempting to use .ajax to retrieve the source HTML of a specific URL (in this case, www.wikipedia.org) and insert it into the body of a document. However, the code provided below is not producing the expected outcome. <!DOCTYPE html> < ...

Using jQuery Datepicker Beforeshowday to dynamically retrieve an array of unavailable dates through Ajax

Currently, I am working on implementing a datepicker that will update an array of unavailable dates. While it successfully works with a PHP variable being passed, the challenge lies in properly returning the data for the option (as it is throwing a console ...

Retrieve information from a web service using PHP function

Is there a way to fetch information from this specific web service using PHP? I'm looking for a straightforward PHP function that can display a list of countries. Information from the Web Service { "valid":true, "id":"0 ...

The functionality of linear mode seems to be malfunctioning when using separate components in the mat-horizontal-stepper

In an effort to break down the components of each step in mat-horizontal-stepper, I have included the following HTML code. <mat-horizontal-stepper [linear]="true" #stepper> <mat-step [stepControl]="selectAdvType"> <ng-template matStep ...

Generating a tree structure using a JavaScript array

Looking to build a tree structure from a given list of data where the paths are represented like: A-->B-->C-->D-->E.. A-->B-->C-->D-->F.. A-->F-->C-->D-->E.. . . . All possible data paths are stored in an array. The de ...

Ways to modify the data within a column for every row in a table without relying on props in Vue.js (specifically Element-ui)

I've been stuck on this issue for quite some time now. I've created a table with 3 columns, and for the first two columns, I can easily display the contents of each row using the prop property. However, for the third column, I need to display inf ...

The function WebForm_DoCallback is not recognized

Encountering an error where WebForm_DoCallback is undefined. UPDATE WebForm_DoCallback("AccountPageControl1", "FileSave~" + fileName, CVFileSavedServerResponse, null, null, true); function CVFileSavedServerResponse(param, context) { } Why isn't ...

Using .htaccess to Handle Empty $_POST Requests

After searching extensively on the internet, I am still unable to find a solution to my problem. I have an .htaccess file that successfully rewrites my query string into the GET variable. However, I have encountered a new issue when dealing with the POST ...

Exploring the Positives and Negatives of Using JQuery and Glow JavaScript Libraries

Is there a detailed analysis available that compares JQuery with the BBC's Glow JavaScript libraries? ...

How to utilize 'this' in a Vue template?

I'm feeling confused: I came across information stating that we can use this in Vue.js templates. But now I'm unsure about which one to use. I decided to experiment with some cases here: new Vue({ el: "#app", data: function() { return { ...

The AngularJs 2 framework encountered an issue with booting up after attempting to combine all TypeScript files into a single JavaScript file

I am currently utilizing Angular 2 with TypeScript (V-1.8) in my project setup. I have configured my tsconfig to output the code into a single .js file. This single.js file includes the necessary code to bootstrap the application, as the boot.ts file is al ...

enhancing look of external tool

I have a third-party widget with inline CSS that displays a table on my website. Is there a way to strip out the inline CSS from the widget before adding it to my page so that only my custom css file styles are applied? The HTML structure of the widget i ...