Having trouble choosing a subitem from a dropdown menu in Vuejs?

An example can be found at https://jsfiddle.net/79epsrmw/. However, the issue arises when targeting the item1 sub-menu in VS Code even after assigning a unique id.

  
  var app = new Vue({
    el: '#app',
    data: {
        menuItems: [
        {
            name: 'Item 1',
          children: [{name: 'Subitem 1'},{name: 'Subitem 2'},{name: 'Subitem 3'}]
        },
        {
            name: 'Item 2'
        }
      ],
        selectedDropdown: 'None'
    },
    methods: {
        setSelectedItem(item) {
        this.selectedDropdown = item;
      }
    },
    ready: function() {
      $('.dropdown-submenu a.test').on("click", function(e){
        $(this).next('ul').toggle();
        e.stopPropagation();
        e.preventDefault();
      });    
    }
  })
.dropdown-submenu {
    position: relative;
}

.dropdown-submenu .dropdown-menu {
    top: 0;
    left: 100%;
    margin-top: -1px;
}
<div class="container" id="app">
  <h2>Vue.js multi-level dropdown example</h2>
  <p>
  Selected element: {{ selectedDropdown }}
  </p>
  
  <div class="dropdown">
    <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Dropdown
    <span class="caret"></span></button>
    <ul class="dropdown-menu">
      <li v-for="item in menuItems" v-bind:class="{'dropdown-submenu': item.children}">
        <a class="test" tabindex="-1" href="#">{{item.name}}<span class="caret" v-if="item.children"></span></a>
        <ul class="dropdown-menu" v-if="item.children">
          <li v-for="child in item.children" :key="child"><a tabindex="-1" href="#" @click="setSelectedItem(child.name)">{{child.name}}</a></li>
        </ul>
      </li>  
    </ul>
  </div>
</div>

Encountering an error stating "Elements in iteration expect to have 'v-bind:key' directives.eslint-plugin-vue. To resolve this, a unique key identifier was set like so: :key="child"

Despite successfully executing in the editor, I am unable to select the sub-menu under item1 in VS Code after setting a unique id.

Answer №1

Take a look at this fiddle

https://jsfiddle.net/negqvmjd/35/

  
  var app = new Vue({
    el: '#app',
    data: function () {
    return {
        menuItems: [
        {
            name: 'Item 1',
          children: [{name: 'Subitem 1'},{name: 'Subitem 2'},{name: 'Subitem 3'}]
        },
        {
          name: 'Item 2',
                    children: []
        }
      ],
        selectedDropdown: 'None'
            }
    },
    methods: {
        setSelectedItem(item,childLength, bool) {
                if(childLength === 0 && bool === false){
    this.selectedDropdown = item;
}
else if(childLength !==0 && bool === true){
    this.selectedDropdown = item;
}
        
      }
    },
    ready: function() {
      $('.dropdown-submenu a.test').on("click", function(e){
        $(this).next('ul').toggle();
        e.stopPropagation();
        e.preventDefault();
      });    
    }
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div class="container" id="app">
  <h2>Vue.js multi-level dropdown example</h2>
  <p>
  Selected element: {{ selectedDropdown }}
  </p>
  
   
  <div class="dropdown">
    <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Dropdown
    <span class="caret"></span></button>
    <ul class="dropdown-menu">
      <li v-for="item in menuItems" v-bind:class="{'dropdown-submenu': item.children.length}">
        <a class="test" tabindex="-1" href="#" @click=setSelectedItem(item.name,item.children.length,false)>{{item.name}}<span class="caret" v-if="item.children.length"></span></a>
        <ul class="dropdown-menu" v-if="item.children.length">
          <li v-for="child in item.children"><a tabindex="-1" href="#" @click="setSelectedItem(child.name,item.children.length,true)">{{child.name}}</a></li>
        </ul>
      </li>  
    </ul>
  </div>
</div>

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

Move the cursor within the text area upon clicking the button

When the "+header" button is clicked, I am looking to automatically position the insertion point inside the text area. Currently, after pressing the button, the text box displays information like address, date, time etc. but the cursor does not start insid ...

What is the best way to address Peer dependency alerts within npm?

Here is a sample package.json that I am using for my application: dependencies : { P1 : “^1.0.0” // with peer dependency of p3 v1 P2 : “^1.0.0” // with peer dependency of p3 v2 } P1 and P2 both have peer dependencies on ...

Anticipate that the typescript tsc will generate an error, yet no error was encountered

While working in the IDE to edit the TypeScript code, an issue was noticed in checkApp.ts with the following warning: Argument type { someWrongParams: any } is not assignable to parameter type AddAppToListParams. Surprisingly, when running tsc, no error ...

What is the recommended approach for utilizing props versus global state within your components when working with JS Frameworks such as Vue?

Currently, I am delving into a larger project using Vue and I find myself contemplating the best practices when it comes to utilizing props versus global Vuex states for accessing data within a component. To elaborate, let's say I have a component re ...

Choosing a value from a dropdown automatically based on the selection of a specific value from another dropdown

Currently, I am working on a project that involves selecting a value from a dropdown menu based on the selection from another dropdown menu. var gender1 = document.querySelector("#gender1"); var gender2 = document.querySelector("#gender2"); gender1.add ...

Is there a way to implement seamless scrolling within an absolute element using Jquery?

Hey there! I recently implemented smooth scrolling on my website, but it seems to only work on single-page layouts. How can I make it function properly within an absolutely positioned scrollable element? Here are the link to my website and the correspond ...

What is the process for exporting a chart into Excel?

My current challenge involves displaying data extracted from a database in the form of a bar chart and then exporting both the data and the chart as an image into an Excel file. While I have successfully displayed the bar chart, I am facing difficulties in ...

How can I utilize jQuery to iterate through every anchor tag on an HTML page?

I am looking to reference all anchor tags on the page that have a parent h2 tag. To achieve this, I need to iterate through each anchor tag that has a parent h2 and add an attribute using jQuery. <body> <h1>not me</h1> <a href ...

An issue encountered while implementing a post method with fetch and Express

I'm just starting out, so I hope my question isn't too basic. My goal is to send a longitude and latitude from client-side JavaScript to a Node.js server using Fetch and Express.js. Below is the HTML code snippet: <!DOCTYPE html> <html ...

Can anyone recommend an easy regular expression to validate date format patterns?

While searching for regex patterns to validate date values in a specific format, I came across numerous options. However, I prefer to allow users to input their own custom date patterns such as: d-mm-yyyy MM/dd/yy yyyy.mm.d I am looking for a ...

Storing and Manipulating a JavaScript Object with Vuex: A New Perspective

Consider a hypothetical JavaScript object class like this: class Car { var engineTurnedOn = false; ... public turnEngineOn() { engineTurnedOn = true } } If I want to turn the engine on, should I create an action called 'turnEngineOn&ap ...

Tips for transitioning from Angular to Angular 2: Overcoming key challenges

Our current Angular project is highly developed, but with the emergence of Angular 2 and its advanced features and improved performance, we are considering migrating our existing work. However, we are concerned about the potential challenges that may ari ...

Having trouble assigning a value to the datapicker through the onchange event and the name attribute in the code below

const stateValues = { code: '', product: '', checked: 'false', jobCardNo: '', openDate: '', completionDate: '', serial: '', technicalNo: '', ...

Creating a new row does not result in the creation of a new span displaying the character count message

Every description field should have its own character counter, with different SpanIDs displayed in respective SpanIds for each new row. How can this be achieved? <div class="row"> <div class="col-s ...

Locate all inputs containing a special attribute name, wherein a portion of the name corresponds to a JavaScript variable

$("td[id^='td' + myvar + '_']") Can someone help me with a solution to substitute the static value of 0 in this code snippet with the dynamic variable myvar? Thanks! ...

Is there a way to display an image in a React Native app using data from a JSON file?

I am currently working with JSON content that includes the path of an image. I need to display this image in my React Native application. What is the best way to render this image? {"aImages":[{"obra_path":"http:\/\/uploa ...

In jQuery, a dropdown selection can be filled with multiple textboxes sharing the same class

I'm experimenting with the idea of using multiple textboxes with the same class filled with different dropdown options that also have the same class. However, I am encountering some issues. When I click on a dropdown option, it changes the value in a ...

Using Facebook authentication in React Native

Currently developing a React Native app and aiming to incorporate Facebook login functionality. The back-end logic for user authentication is handled by an API in Node.js. Utilizing passport.js to enable users to log in using either Facebook or Email cre ...

React-Redux Error: The function this.props.AppendCharacter is not defined

I have been looking for a solution to my issue but couldn't find anything that matches it. I am working on creating a calculator app using React & Redux, and whenever I click on one of the number buttons, I receive an error message saying "this.props. ...

jQuery Form Validator: requiring double submission

I've been working on implementing the Form Validator using Jquery. After some testing, I noticed that I have to click the submit button twice before the validation kicks in. Why is that? The script is housed in a separate file and included in my proj ...