Can the sidebar in Vue be toggled using a method?

In a <b-table>, I want to add an action button to each item:

<b-table :items="data" :fields="fields">
  <template v-slot:cell(actions)="data">
    <b-button v-on:click="doSomething(data.index)">Do Something</b-button>
  </template>
</b-table>

Next, I have a Form located in a sidebar

<b-sidebar id="do-something-form" title="Do something" right>
...
</b-sidebar>

When the action button is clicked, I want to take a certain action in my methods:

methods: {
    doSomething(id) {
        sidebar.form.id = id
        sidebar.show().onSubmit(() => {
           axio...
           refresh(<b-table>)
        })
    }
}

Unfortunately, this approach is not valid. I couldn't find any information in the Bootstrap Vue documentation on how to interact from Vue to Bootstrap components. Any suggestions?

Answer №1

To toggle the sidebar, you can trigger an event on $root with the id of the sidebar you want to open:

this.$root.$emit('bv::toggle::collapse', 'my-sidebar-id')

<b-collapse> and <b-sidebar> both listen for the same event, which is why the event is named collapse.

new Vue({
  el: '#app',
  methods: {
    openSidebar() {
      this.$root.$emit('bv::toggle::collapse', 'my-sidebar')
    }
  }
})
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="55373a3a21262127342515617b607b67">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdafa2a2b9beb9bfacbde0bbb8a88dffe3fcfae3fc">[email protected]</a>/dist/bootstrap-vue.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7b5b8b8a3a4a3a5b6a7faa1a2b297e5f9e6e0f9e6">[email protected]</a>/dist/bootstrap-vue.js"></script>

<div id="app">
  <b-sidebar id="my-sidebar" right>
    My sidebar
  </b-sidebar>

  <b-btn @click="openSidebar">
    Open sidebar
  </b-btn>
</div>

Another approach is to bind a boolean property to the v-model of the sidebar and set it to true when you want the sidebar to open.

new Vue({
  el: '#app',
  data() {
    return {
      isSidebarOpen: false
    }
  },
  methods: {
    openSidebar() {
      this.isSidebarOpen = true
    }
  }
})
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="accec3c3d8dfd8decddcec988299829e">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a2825253e393e382b3a673c3f2f0a78647b7d647b">[email protected]</a>/dist/bootstrap-vue.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="25474a4a5156515744550853504065170b14120b14">[email protected]</a>/dist/bootstrap-vue.js"></script>

<div id="app">
  <b-sidebar v-model="isSidebarOpen" right>
    My sidebar
  </b-sidebar>

  <b-btn @click="openSidebar">
    Open sidebar
  </b-btn>
</div>

Answer №2

Furthermore, by utilizing the sidebar's pre-built public methods such as show, hide, or toggle, you can easily manage its visibility. Simply include a reference to your sidebar like so:

<b-sidebar ref="mySidebar" id="do-it-form">
...
</b-sidebar>

Then, whenever necessary within your methods, you can effortlessly execute any of these actions:

this.$refs.mysidebar.show();
this.$refs.mysidebar.hide();
this.$refs.mysidebar.toggle();

Answer №3

To control the visibility of the sidebar, you can simply set a boolean value to the visible prop of the b-sidebar component and toggle it as needed.

<b-sidebar ref="mySidebar" id="do-it-form" :visible="showSidebar">
...
</b-sidebar>

For toggling the visibility, you can utilize the following:

data: {
   showSidebar: false, //initially hidden
},
methods: {
   toggleSidebar(){
      this.showSidebar = !this.showSidebar
   }
}

This method may not be ideal if the sidebar visibility needs to be updated by multiple components. It's more suitable for cases where the sidebar visibility changes are controlled by a central store using a boolean value.

For example:

const state = {
  showSidebar: null
}

const mutations: {
  toggleSidebar(state, payload){
     if (payload) { 
            state.showSidebar = payload;
     } else {
            state.showSidebar = !state.showSidebar;
     }
  }
}

In your components:

computed: {
   showSidebar(){
     return this.$store.state.showSidebar
   }, //initially hidden
},
methods: {
   toggleSidebar(){
      this.$store.commit("toggleSidebar");
   }
}

Your updated sidebar component configuration:

<b-sidebar ref="mySidebar" id="do-it-form" :visible="showSidebar" @change="updateSidebar">
...
</b-sidebar>

And the method:

methods: {
   updateSidebar(value){
      this.$store.commit("toggleSidebar", value);
   }
}

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

Display the JSON data by pressing Enter key instead of clicking on the submit button

I am facing an issue with my MVC view where clicking the submit button posts data using Ajax to the Controller. The controller returns a JSON result containing messages which are then displayed on the View. The problem arises when I press Enter after seein ...

A messaging application powered by socket.io and the Express JS framework

I am currently learning Node.js and I am encountering an issue with using socket.id to identify logged in users on the client side using their email id and password. The verification process happens on the server side, and if successful, the user's so ...

Steps for Displaying Data from API Response in Vue.js

Immediately rendering the following template, without waiting for the API call to complete. I came up with a solution using v-if to prevent elements from rendering until the data is available. However, this seems to go against the DRY principle as I have ...

React JS: Incorporating Multiple Placeholder Objects within Components

Apologies if this question is a duplicate, but I haven't found any helpful answers yet. I'm new to React and JavaScript. I am looking to include multiple objects inside a component: For example: src={url} name={text} subTitle={subtext} My in ...

Can anyone explain why my navbar text is not aligning in the center?

I am struggling to center the text in one of my two navbars. As a newcomer to both navbars and bootstrap, I am having difficulty figuring out why I can't achieve this. Should I be making changes on the bootstrap side or can it be fixed within the < ...

CSS animations for loading page content

Currently, I am incorporating animations into my project using HTML5 and CSS3, and the progress has been smooth. I have been able to achieve effects such as: #someDivId { position: absolute; background:rgba(255,0,0,0.75); transition: all 0.7s ...

Unable to access the property '__reactAutoBindMap' as it is undefined

I've been struggling with setting up server side rendering with React for the past week. It's a new project using an express server and I'm trying to render a simple hello world react app that utilizes react-router-component. To get some he ...

JQuery - Issue: Invalid syntax detected in the expression: #

I'm facing an issue with some tabs inside an accordion that don't seem to be functioning properly. The console is showing the following error: Error: Syntax error, unrecognized expression: # Despite searching for a solution online, I can&apos ...

Integrate my API with HTML using J.Query/Ajax technology

Finally, after much effort, I have successfully created a JSON java API. My API design is simple and based on Interstellar movie details: { "title": "Interstellar", "release": "2014-11-05", "vote": 8, "overview": "Interstellar chronicl ...

Using Selenium to continuously scroll to the bottom of the webpage

Selenium: I am new to WebDriverJS. I have experimented with this method in Java. Long repeat = 0l, scrollHeight = 0l, returnHeight = 0l; while(true){ if (repeat == 0) { returnHeight = (Long) jse.executeScript("var scroll =document.documentEle ...

Is it possible to create a button that can bring in a .css file?

Is there a way to create a button that imports styles from a .css file, or is it possible to change multiple CSS properties with buttons to create different website themes? This is the CSS file I have: .body { background-image: url("example.png"); } ...

Python raises a KeyError if JQuery is included

I have encountered an issue with the code snippet below, where I am attempting to define a variable within the HTML. Oddly enough, when I exclude the JQuery script, everything functions as expected. However, upon reintroducing the JQuery script, the functi ...

What is the best way to imitate a DOM in order to effectively test a Vue application with Jest that incorporates Xterm.js?

I've created a Vue component that displays an Xterm.js terminal. Terminal.vue <template> <div id="terminal"></div> </template> <script> import Vue from 'vue'; import { Terminal } from 'xterm/lib/public ...

Information released by JavaScript through AJAX and JSON

Hello everyone, I've been trying to merge two different Ajax codes together and it's been quite a challenge. As a novice, I know I may sound ridiculous but I really need some help... My goal is to convert an array into JSON and display the data ...

A JavaScript function written without the use of curly braces

What makes a function good is how it is declared: export declare class SOMETHING implements OnDestroy { sayHello() { // some code to say hello } } However, while exploring the node_modules (specifically in angular material), I stumbled up ...

Displaying the Yii form directly on the page upon loading, rather than enclosed within a jQuery dialog box

After studying this yii wiki page, I encountered an issue where the form is supposed to appear within a jQuery dialog box, but it opens immediately when the page loads instead. Upon further investigation, I discovered that removing the success callback fr ...

Creating a progress bar with blank spaces using HTML, CSS, and JavaScript

Upon running the code below, we encounter an issue when the animation starts. The desired effect is to color the first ten percent of the element, then continue coloring incrementally until reaching 80%. However, as it stands now, the animation appears mes ...

Encountering a console error: Prop type validation failed for the `Rating` component with the message that the prop `value` is required but is currently `undefined`

I am encountering a proptype error which is causing an issue with the URL display on my Chrome browser. Instead of showing a proper address, I am seeing the URL as undefined like this: http://localhost:3000/order/undefined Instead of undefined, I should h ...

Unable to locate or modify an item within an array

I have a unique way of organizing my collection, with an array inside. Here's how it looks: const postsSchema = mongoose.Schema({ posts: {type: Array}, }) Now, I want to search for a specific document within this collection. I attempted the follo ...

Having trouble with IE7 - unable to interact with elements below popup form

<script type="text/javascript">var switchTo5x=true;</script> <script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script> <script type="text/javascript">stLight.options({publisher:'b42661f5-2dc5 ...