Home > Enterprise >  Toggle Sidebar component with button from Navbar Component
Toggle Sidebar component with button from Navbar Component

Time:03-19

I'm trying to learn Laravel with Vuejs (v3). I have 3 components: App.vue, Navbar.vue, and Sidebar.vue

What I'm trying to do is, onclick of sidebar-btn:

  1. Change value of variable isSidebarActive to !isSidebarActive ---- DONE
  2. Change class of fontawesome (dependent on isSidebarActive). ---- DONE
  3. Show Sidebar.vue (dependent on isSidebarActive)

I tried using props but error says I can't change the value, so I tried using emits but I still can't seem to get it right.

app.js

require('./bootstrap');

import { createApp }    from 'vue'
import App              from './App.vue'
import router           from './routes'

// Partials
import Navbar           from './components/Navbar.vue'
import Sidebar          from './components/Sidebar.vue'

createApp(App)
.component('navbar', Navbar)
.component('sidebar', Sidebar)
.use(router)
.mount('#app')

App.vue

<template>
    <navbar></navbar>
    <sidebar v-bind:></sidebar>

    <router-view></router-view>
</template>

<script>
export default {
    name: "App",
    data() {
        return {
            isSidebarActive: false,
        };
    },
}
</script>

Navbar.vue

<template>
<nav >
    <div >
        <div  >
            <span >
                Hello World!
            </span>

            <!-- Button to toggle Sidebar -->
            <span  id="sidebar-btn" style="border: 1px white" @click="toggleSidebar()">
                <i v-bind: title="Sidebar Menu"></i>
            </span>
        </div>
    </div>
</nav>
</template>

<script>
export default {
    name: "Navbar",
    data() {
        return {
            isSidebarActive: false,
        };
    },
    emits: ['isSidebarActive'],
    methods: {
        toggleSidebar:function () {
            this.isSidebarActive = !this.isSidebarActive
            this.$emit("isSidebarActive", this.isSidebarActive)
        },
    },
}
</script>

CodePudding user response:

Please take a look at following snippet:

const app = Vue.createApp({
  data() {
    return {
      isSidebarActive: false,
    };
  },
  methods: {
    handleSidebar() { //            
  • Related