The Vue.js application is failing to toggle the integrated code

I am new to using Vue and I am trying to create a vertical navigation bar. When the menu icon is clicked, the navbar should toggle.
Here is my menu icon code:

    <button type="button" id="sidebarCollapse" class="btn btn-info [collapsed?'':'sidebar']"  >
    <i class="fas fa-align-left"></i>
    </button>

When the menu icon is toggled, I want to show the nav sidebar.

   <nav id="sidebar" class="sidebar">
    </nav>

Here is my Vue code:

  new Vue({
   e1:'#app',
   data:{
       collapsed:true
   }
})

Nothing is displaying and I am new to Vue. Can anyone help me figure out what is wrong?

Updated Code

Position.vue

  <template>
   <div class="wrapper">
     <nav id="sidebar" class="sidebar" v-if="showSidebar">  
       <ul class="list-unstyled component">
            <li class="active">
                <a href="#homeSubMenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">Home</a>
                <ul class="collapse list-unstyled" id="homeSubMenu">
                    <li class="dropdown-menu-mn">
                        <a href="#">Home1</a>
                        <a href="#">Home2</a>
                    </li>
                </ul>
            </li>                                                 
        </ul>
    </nav>        
        <div id="content">
            <nav>
                <div class="navbar navbar-expand-lg navbar-light bg-light">
                    <div class="container-fluid">

                        <button type="button" id="sidebarCollapse" class="btn btn-info" @click="toggleSidebar">
                          <i class="fas fa-align-left"></i>
                        </button>
                    </div>
                </div>
            </nav>
        </div>        
    </div>  
   </template>

  <script>
    new Vue({
    el:'#app',
    data: {
   showSidebar: false
    },
    methods: {
  toggleSidebar: function() {
     this.showSidebar = !this.showSidebar;
  }}})            
  </script>

update script tag

    <script>
    export default{
    data() {
   showSidebar: false
    },
     toggleSidebar(){
     this.showSidebar = !this.showSidebar;
    } };   
   </script>

However, it still does not work. Only the menu button appears but the toggle functionality is not working. Can anyone point out where I am making a mistake?

Answer №1

Ensure that the button has an event listener with @click

    <button type="button" id="sidebarCollapse" class="btn btn-info" @click="toggleSidebar">
       <i class="fas fa-align-left"></i>
    </button>

Use a directive v-if on the sidebar element to toggle its visibility

   <nav id="sidebar" class="sidebar" v-if="showSidebar">
    </nav>

Create a method to handle the click event, update the value used in the v-if directive

  new Vue({
   el:'#app',
   data: {
       showSidebar: false
   },
   methods: {
      toggleSidebar: function() {
         this.showSidebar = !this.showSidebar;
      }
   }
  })

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

How to add suspense and implement lazy loading for a modal using Material-UI

Currently, I am implementing <Suspense /> and lazy() to enhance the performance of my project. While everything seems to be working smoothly, I have observed some minor changes in DOM handling that are causing me slight confusion. Consider this scen ...

Issue with Firefox browser: Arrow keys do not function properly for input tags in Twitter Bootstrap drop down menu

Requirement I need to include a login form inside the dropdown menu with username and password fields. Everything is working fine, except for one issue: Issue When typing, I am unable to use the arrow keys (up/down) in Firefox. This functionality works ...

What is the method for incorporating a timeout in a promise?

After exploring various methods for adding timeouts to promises, it appears that most rely on the setTimeout() function. Here is the formal definition: The setTimeout() function executes a specified function or evaluates an expression after a set number of ...

Halt period indicated in the document specifying the designated timeframe

If I have two files named index.php and fetch.php The contents of index.php are as follows: <script> $(document).ready(function(){ setInterval(function(){ $('#fetch').load('fetch.php') }, 1000); }); </sc ...

Is it possible for a button to simultaneously redirect and execute a function using asynchronous JavaScript?

After browsing through several related posts, I realized that most of them were using href to redirect to a completely new webpage. However, in my JavaScript code, I have a button that utilizes the Material-UI <Link>. <Button component={Link} to= ...

Is there a different option than jQuery.ajaxSettings.traditional for use with XMLHttpRequest?

Is there a different option similar to jQuery.ajaxSettings.traditional for xmlhttprequest? or What is the method to serialize query parameters for an xmlhttprequest? ...

Maintaining the $index value across all pagination pages in AngularJS while matching it with the items in the data list

Is there a way to maintain the original $index numbers in my list data after pagination? For example, if data.length is 50 and they start from index 0, the first page contains 10 items ending at index 9. The next item on the second page should start at in ...

Tips for personalizing text and icon colors in the TableSortText element of Material-ui

My Goal: I aim to empower users with the ability to apply customized styles to my EnhancedTable component by utilizing a styles object containing properties like headCellColor, headCellBackgroundColor, bodyCellColor, bodyCellBackgroundColor, and more. The ...

Safari-exclusive: Google Maps API dynamically altering page aesthetics post-loading

Recently, I encountered a peculiar problem. Upon loading a page, the text displayed with full opacity. However, upon the Google Maps API loading after 2 seconds, the entire page's styling suddenly changed. It was as if the text on the page became less ...

Displaying JavaScript values one by one using a for loop and alert

Having an issue with looping through a JSON array in JavaScript. I am trying to extract only SG_J1001 and SG_LS01, but it's not working as expected. The result is coming out like this [{"regis ....... var item = JSON.stringify(data['code'] ...

How do you switch selection to "hold" mode using Javascript?

In my Markdown preview area, clicking on text will cause the preview area to switch to a markdown source editor automatically, with the cursor jumping to the position corresponding to where it was clicked. function onMouseDown(e) { const range = documen ...

Ways to identify when a user presses the back or forward arrow on a browser using JavaScript or jQuery for a non-single page application (

There are only 2 routes available: / and /about When on the following URLs: localhost:8080 -> it displays the home page localhost:8080/about -> it shows the about page If a user opens the home page, clicks on the about button, and goes to the abou ...

Utilizing Route Parameters in Node.js

frontend.jade doctype html html head meta(charset='utf-8') //if lt IE 9 script(type='text/javascript', src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js') // [if gte IE 9] <! scr ...

Different option for key press identification

My JavaScript skills are still at a beginner level and I've come across a bug that's causing me trouble. The issue is with keyCode not working on mobile devices (Chrome). It seems that mobile devices do not support keyCode. I think I could use ...

Incorporate PNG files with pre-defined labels in a React element

In my application, there is a collection of PNG images with filenames consisting of only 2 letters like aa.png, ab.png, ac.png, and so on. Additionally, there is an API endpoint that retrieves an array of objects with a property "name" containing 3 letter ...

Troubleshooting the "@material-ui/core" issue in React: Step-by-step guide

Issue with React: Unable to locate the '@material-ui/core' module in 'C:\Users\user\Downloads\inTech'22-Web Development (EDUGEN)\edu-gen\src\components' Resolution Command: To resolve, run npm in ...

The declaration file for module 'react/jsx-runtime' could not be located

While using material-ui in a react project with a typescript template, everything is functioning well. However, I have encountered an issue where multiple lines of code are showing red lines as the code renders. The error message being displayed is: Coul ...

Using async await in node.js allows you to bypass the need for a second await statement when

As I dive into using await async in my Node.js ES6 code... async insertIngot(body, callback) { console.log('*** ItemsRepository.insertIngot'); console.log(body); const data = await this.getItemsTest(); console.log('*** ge ...

Combining Jquery with Append to Dynamically Update PHP Variables

Code Snippet (index.html) <script> $(document).ready(function() { var interval = setInterval(function() { $.get("load_txt.php", { 'var1': 4, 'var2' : 52}, function(data){ $('#msg' ...

Use PHP to highlight the row that has been selected in an HTML table

I am currently working on a project where I have styled multiple HTML tables on my website using alternating gray and white bands. Now, my goal is to highlight the selected row in a darker shade of gray. I have experimented with various solutions, and the ...