What is the best way to design a navigation bar for a one-page application using Vue?

Currently, I am developing a Vuejs single-page application and I'm exploring ways to implement a navbar that can toggle the visibility of different sections within the app upon clicking. While I have successfully designed the navbar layout, I am encountering difficulties in making it control the display of components. My initial approach involved having the navbar component manipulate an array dictating which components should be shown, but this method proved unsuccessful as the component couldn't access the array. What alternative solution would you recommend for achieving this functionality?

Answer №1

If you're not utilizing Vue-Router, this could be the solution you've been seeking.

However, for most Vue single page applications (SPAs), it is recommended to use Vue-Router.

<!DOCTYPE html>
<html>
<head>
  <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6d0b0203192d594315">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="45333020312c233c05776b3d">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
</head>
<body>
  <div id="app">
    <v-app>
      <v-main>
        <template>
  <div>
    
    <v-tabs
      v-model="tab"
      background-color="blue accent-4"
      class="elevation-2"
      dark
      :centered="centered"
      :grow="grow"
      :vertical="vertical"
      :right="right"
      :prev-icon="prevIcon ? 'mdi-arrow-left-bold-box-outline' : undefined"
      :next-icon="nextIcon ? 'mdi-arrow-right-bold-box-outline' : undefined"
      :icons-and-text="icons"
    >
      <v-tabs-slider></v-tabs-slider>

      <v-tab
        v-for="i in tabs"
        :key="i"
        :href="`#tab-${i}`"
      >
        Tab {{ i }}
      </v-tab>

      <v-tab-item
        v-for="i in tabs"
        :key="i"
        :value="'tab-' + i"
      >
        <v-card
          flat
          tile
        >
          <v-card-text>{{ text }}</v-card-text>
        </v-card>
      </v-tab-item>
    </v-tabs>
  </div>
</template>
      </v-main>
    </v-app>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b2d2e3e1b697523">[email protected]</a>/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="57212232233e312e1765792f">[email protected]</a>/dist/vuetify.js"></script>
  <script>
    new Vue({
      el: '#app',
      vuetify: new Vuetify(),
      data: () => ({
      tab: null,
        text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.',
        icons: false,
        centered: false,
        grow: false,
        vertical: false,
        prevIcon: false,
        nextIcon: false,
        right: false,
        tabs: 3,
    }),
    })
  </script>
</body>
</html>

Answer №2

Recently, I worked on a project using vue-router. While the syntax in the initial code snippet may be a bit different due to my familiarity with writing in vue CLI, the process involves inserting the tag in App.vue within the main tag, setting up your router page, and configuring your router component.

If you're looking to get started, I suggest creating a new vue cli app.

To do so, open your terminal and run the following commands: vue create hello-world (include vue-router during the creation steps prompt), and then add vuetify by running vue add vuetify!

<!DOCTYPE html>
<html>
<head>
  <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74121b1a0034405a0c">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88fefdedfce1eef1c8baa6f0">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
</head>
<body>
  <div id="app">
    <v-app>
      <v-main>
        <TopToolbar class="topTool"></TopToolbar>
          <router-view></router-view>
        <BottomNav class="bottomN"></BottomNav>
      </v-main>
    </v-app>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e686b7b5e2c3066">[email protected]</a>/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfb9baaabba6a9b68ffde1b7">[email protected]</a>/dist/vuetify.js"></script>
  <script>
  import BottomNav from 'path';
    new Vue({
      el: '#app',
      vuetify: new Vuetify(),
      components: {TopToolbar, BottomNav},
      data: () => ({
      
      }),
    })
  </script>
</body>
</html>

<template>
  <v-bottom-navigation
    scroll-threshold="800"
    absolute
    color="primary"
    light
    grow
    background-color="primary"
    height="56"
  >
    <v-btn value="scan" :to="{ name: 'Scan'}">
      <span v-if="this.$route.name != 'Scan'" style="color: #fff">Scan</span>
      <v-icon v-if="this.$route.name != 'Scan'" size="24" color="#fff">mdi-barcode-scan</v-icon>
      <v-icon v-else size="24" color="primary">mdi-barcode-scan</v-icon>
    </v-btn>

    <v-btn value="create" :to="{ path: '/'}">
      <span v-if="this.$route.name != 'Create'" style="color: #fff">Create</span>
      <v-icon v-if="this.$route.name != 'Create'" size="24" color="#fff">mdi-barcode</v-icon>
      <v-icon v-else size="24" color="primary">mdi-barcode</v-icon>
    </v-btn>

    <v-btn value="print" :to="{ name: 'Print'}">
      <span v-if="this.$route.name != 'Print'" style="color: #fff">Print</span>
      <v-icon v-if="this.$route.name != 'Print'" size="24" color="#fff">mdi-printer</v-icon>
      <v-icon v-else size="24" color="primary">mdi-printer</v-icon>
    </v-btn>
  </v-bottom-navigation>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component({})
export default class BottomNav extends Vue {}
</script>

<style scoped>

</style>

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes = [
  {
    path: '/scan',
    name: 'Scan',
    component: () => import('../views/Scan.vue'),
  },
  {
    path: '/',
    name: 'Create',
    component: () => import('../views/Create.vue'),
  },
  {
    path: '/print',
    name: 'Print',
    component: () => import('../views/Print.vue'),
  }
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

export default router;

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

What is the best way to acquire the href value from this source?

Looking to extract the dynamic value "3 Sent" from the html snippet provided. How can this be achieved? <ul class="nav nav-tabs some-tabs"> <li class="active"> <a href="#accepted" data-toggle="tab">1 Accepted</ ...

What is causing the unexpected impact of the "Product Quick View" JavaScript plugin on divs that are not being activated by user interaction?

As a newcomer to web design, I have implemented the "Product-Quick-View" plugin from CodyHouse on my website. Upon clicking the DEMO button and inspecting the code, you will find the following: <body> <header> <h1>Product Q ...

What is the best way to strip out a changing segment of text from a string?

let: string str = "a=<random text> a=pattern:<random text (may be fixed length)> a=<random text>"; In the given string above, let's assume that a= and pattern are constants. It is possible that there may or may not be a ...

Decipher the JSON data for a Facebook cover photo

I am utilizing the Facebook Graph API to retrieve the user's cover picture. By accessing the link provided at , a JSON object containing the picture link is returned. How can I fetch this link using JQuery or JavaScript? Here is my attempt: HTML: & ...

What should be triggered when clicking on the cancel button in Bootstrap's modal: `close()` or `dismiss()`?

Bootstrap's modal offers two methods for hiding the dialog: close(result) (Type: function) - Used to close a modal by providing a result. dismiss(reason) (Type: function) - Used to dismiss a modal and provide a reason. Should I use close when the u ...

Resposiveness of force-directed graph is lost

const container = document.getElementById("container"); const svgElement = d3.select(container).append("svg") // Get the width and height computed by CSS. let width = container.clientWidth; let height = container.clientHeight; const colorScale = d3.scale ...

What is the best way to execute a function based on its name, which is provided as a parameter

Is there a better way to call a function by its name, passed as a parameter in JavaScript? Here's my scenario: I have a switch case where I need to set the data for an API ajax call. Once the ajax call is complete, I want to call a specific print func ...

A guide to efficiently passing props in a Vue.js application connected to Express with MongoDB

I am in the process of creating a simple chat application using Vue.js, Node, Express, and MongoDB. The app starts with a welcome page where users can input their names (refer to: Welcome.vue). After entering their name, users are directed to Posts.vue, pa ...

Avoid the need for users to manually input dates in the Custom Date Picker

After referencing this custom Date picker in ExtJs with only month and year field, I successfully implemented it. However, I am facing an issue where manual entry into the date field is not disabled. My goal is to restrict input for that field solely thr ...

Developing a universal.css and universal.js file for a custom WordPress theme

I have developed a custom WordPress theme with an extensive amount of code. To manage the numerous style and script files, I have segmented them into multiple individual files. To integrate all these files into my template, I utilized the following code w ...

Trigger event upon variable modification

Currently, I am working on a school project that involves creating a website where users can listen to music together. I have implemented a button that allows the user to listen to the same song another user is currently playing at the right position. Howe ...

The jQuery change event is not triggered for <input type="file"> when a file is dropped on the label

I am currently developing a drag and drop file uploader that can be activated by either clicking the label or dragging a file onto the label. The input field includes a jQuery on change event that is triggered when a file is selected. However, it only see ...

Is there a way to modify AJAX response HTML and seamlessly proceed with replacement using jQuery?

I am working on an AJAX function that retrieves new HTML content and updates the form data in response.html. However, there is a specific attribute that needs to be modified before the replacement can occur. Despite my best efforts, I have been struggling ...

What is the reason behind router.base not functioning properly for static sources while running 'npm run build' in Nuxt.js?

Customizing Nuxt Configuration const BASE_PATH = `/${process.env.CATEGORY.toLowerCase()}/`; export default { router : { base : BASE_PATH }, } In addition, there is a static source for an image in the component: <img src="/mockups/macbookpro_01. ...

What is the best way to conceal my class element if the data-reviews number is under 5?

I have been experimenting with basic JavaScript for the data-reviews="2" scenario and it worked successfully. However, what I am aiming for is to hide the entire <span> section when the value of data-reviews is less than 5 or any specific ...

How to Utilize Class Members in a Callback Function in Angular 12 with Capacitor Version 3

When I click the "Device Hardware Back Button" using Capacitor 3.0, I'm trying to navigate to the parent component with the code below. The device back button is working correctly, but I'm facing an issue where I can't access class members i ...

What is the procedure for selecting an element based on its child containing specifically filtered text?

Imagine a webpage with the following elements: <div data-search="type1"> any HTML <!-- .click is a child of any level --> <span class="click" data-source="page1.html">blue</span> <!-- let's call it "click1 ...

Expanding all rows with the same name in a Vuetify expandable table

I have noticed an issue with the expandable tables in Vuetify, where if two entries in the table have the same name, clicking on one row to expand it also expands another row with the same name. Is there a way to prevent this from happening? To see the pr ...

Tips for resolving the issue: SyntaxError - Unexpected token import

I've encountered this error in the past and have looked at other solutions, but none of them seem to work for my specific issue. My package.json file includes the following dependencies: "dependencies": { "axios": "^0.15.2", "babel": "^6.5. ...

The output of jquery's val() function will not show the actual value

Is it proper to use html() for setting content in non-form elements like divs? This question has come up a few times, which I wasn't aware of. I've been working on setting a value after fetching comments through a $.ajax call. When I check the v ...