Refresh the page to change the section using vue.js

I am currently working on a website using Laravel and Vue.js. I require two separate sections for the site:

Within the resource/js/app.js file, I have included the main components as follows:

require('./bootstrap');

import VueRouter from "vue-router";
import Frontend from "./frontend/Index";
import Admin from "./backend/Index";
import router from "./routes";

window.Vue = require('vue');
Vue.use(VueRouter);

const app = new Vue({
    el: '#app',
    router,
    components: {
        "index": Frontend,
        "admin": Admin,
    }
});

In the routes.js file:

import VueRouter from 'vue-router';
import Home from './frontend/Dashboard';
import Authors from './frontend/authors/Authors';
import Admin from './backend/Dashboard';

const routes = [
    {
        path: "/",
        component: Home,
        name: "home",
    },
    {
        path: "/authors",
        component: Authors,
        name: "authors",
    },
    {
        path: "/admin",
        component: Admin,
        name: "admin",
    }
]

const router = new VueRouter({
    routes,
    mode: "history",
})

export default router;

A challenge I am facing is when accessing https://www.example.com/authors via the browser it loads correctly with the desired template. However, if I navigate to it from the admin section, it loads in the Admin template.

The organization of files is structured as below:

  • resources
    • js
    • backend
      • Index.vue
      • Dashboard.vue
    • frontend
      • Index.vue
      • Dashboard.vue
      • Authors
        • Authors.vue

When on www.example.com, the main layout loaded is from resource/js/frontend/Index.vue.

Conversely, when on www.example.com/admin, the main layout loaded is from resource/js/backend/Index.vue

If I directly use the URL via the browser, the main layouts load correctly. However, if I utilize

<router-link class="btn nav-button" :to="{name: 'authors'}">Author</router-link>

from the admin section, the authors component gets loaded within the admin layout instead of the frontend layout.

Answer №1

When using Vue-Router, it only swaps out the component loaded in its router-view element, rather than redirecting to a new page. This is advantageous for single page applications.

If your project does not require a single page application and consists mainly of Vue snippets within HTML/CSS files, it is recommended to handle routing without vue-router in Laravel by defining layouts in your HTML pages.

For projects where most or all work is done within a single Vue application, you can create a top-level component that manages layout rendering around different views like so:

// App.vue

<template lang="html">
  <component
    :is="currentLayout"
  >
    <router-view :layout.sync="layout" />
  </component>
</template>

<script>
import DefaultLayout from '../frontend/Index.vue';
import AdminLayout from '../backend/Index.vue';

const LAYOUTS = {
  frontend: DefaultLayout,
  backend: AdminLayout
}

export default {
  computed: {
    currentLayout() {
      return LAYOUTS[this.layout];
    }
  },
  data() {
    return {
      layout: 'frontend',
    };
  },
};
</script>

// Backend/Dashboard.vue
<template>...</template>

<script>
export default {
  created() {
    this.$emit('update:layout', 'backend')
  }
}
</script>

In order to switch between layouts, you can emit events directly from your top-level views as demonstrated in the example, or use Vuex store. Emitting layouts for every view may not be the most efficient method but works effectively.

Alternatively, you could separate admin and default functionalities into different Vue applications. However, maintaining multiple large apps with separate routes can become complex. Consider setting up a fallback route to redirect users to another application if needed:

const routes = [
...
...
...
  {
    path: "*",
    beforeEnter: (to, from, next) => {
    window.location.href('www.example.com')
  }
]

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 process for incorporating an external script into my Vue methods?

After a user registers, I need to send them a confirmation email using vue.js. I am looking to implement the script provided by . How can I incorporate the "Email.send" method into my vue.js application? <script src="https://smtpjs.com/v3/smtp.js"> ...

Can we use a switch statement instead of having multiple @Input()s in Angular?

When passing an attribute into my Angular component like this: <my-component myAttribute></my-component> I aim to modify a variable within the component that controls the CSS properties for width and height. To simplify, I have predefined at ...

Dual Networked Socket.IO Connection

I have set up a node.js server with an angular.js frontent and I am facing a problem with Socket.IO connections. The issue arises when double Socket.IO connections open, causing my page to hang. var self = this; self.app = express(); self.http = http.Ser ...

Ways to verify every entered word without having to click a button

My goal is to implement real-time word checking in a textarea using JavaScript/Angular. I want to validate each word as users are typing it out. What is the best approach for achieving this? ...

Responsive design with Flexbox, interactive graphics using canvas, and dynamic content resizing

I'm having difficulties with my canvas-based application. I have multiple canvases, each wrapped in a div container alongside other content. These containers are then wrapped in an "hbox" container. The objective is to create a dynamic grid of canvas ...

When `focus` is bound to a jQuery event handler, the behavior of the select element becomes erratic on

What causes the odd behavior where users need to click twice on a select-option for it to drop down/up after binding an eventhandler to the focus event using jQuery? $('input, select, textarea').focus(function() { $(this).addClass('input_ ...

Elements in Motion

Working on a parallax effect, I've managed to assign unique scroll speeds to (almost) every element. Moreover, these elements are programmed not to activate their scroll speed until they enter the viewport. Below is the JavaScript code for trigger co ...

What is the best way to extract an object by its specific id using json-server?

I am attempting to retrieve an object by its id using json-server. If I only return a single variable (one JSON) in the module.exports of the database file, everything works fine. However, if I try to return an object with multiple variables, I encounter a ...

A plethora of color choices in a Multi-select Box

Hi there! I am facing an issue with dynamically adding multiple select boxes. Currently, I have 4 color-coded options under the selection boxes, which work fine when there is only one box. However, when I add more than one select box, the color coding doe ...

Vue-jest was unable to gather coverage data from a Vue file

Greetings! As a newcomer to Vue and Jest, I recently integrated Jest into an existing Vue project. My goal is to obtain test coverage results from .js and .vue files. However, I have encountered some difficulties in the process. Upon attempting to run ...

What is the best way to create a clickable background for a modal window?

I am looking to add a chatbox feature to my website and have been utilizing Bootstrap Modal for this purpose. My goal is to keep the modal open even when the user clicks outside of it, while still allowing them to interact with the background of the websi ...

What is the method for accessing a local XML file with $.ajax?

Currently, I am working on developing a Firefox extension that requires reading a local XML file. However, I have encountered an issue with using $.ajax to read the file. Here is a snippet of my code: $.ajax({ type: "GET", url: "file:/// ...

Save a PHP variable and then use it on an HTML page

Is there a way to preserve the value of LAST_INSERT_ID(), also known as Case_ID, so that it can be accessed in another HTML page? If so, what would be the best approach to achieve this? $query.= "insert into Picture (Case_Pic,Case_ID) values ...

Anchor tags are not visible to Jquery

My issue is with integrating JQUERY and PHP. In my external PHP file, I have the following echo statement - `echo ("<a href='#' id='bb'>hello</a>"); Similarly, in my external js file, I have this JQUERY code - $(' ...

Guide to adding an image with feathers.js and multer:

I am currently working on integrating feathers.js with React for my project and I am facing an issue with uploading images. I have tried using multer and busboy for handling the upload, but I am unable to successfully upload the image or access it through ...

Error encountered during installation of Vuetify in Nuxt: "npm err! [email protected] install: `node build.js || nodejs build.js`"

After creating a Nuxt app using npx create-nuxt-app when running the dev server with npm run dev, I encountered the following error: ╭─────────────────────────────────────── ...

Looking to minimize the amount of HTML code in Angularjs by utilizing ng-repeat

Working with some HTML <tr class="matrix_row" ng-repeat="process in matrixCtrl.processes | filter : { park: parentIndex } track by $index"> <td class="properties" ng-click="dashboardCtrl.currParam=0; dashboardCtrl.currentProcess=process"> ...

Using a combination of stringify, regular expressions, and parsing to manipulate objects

As I review code for a significant pull request from a new developer, I notice their unconventional approach to editing javascript objects. They utilize JSON.stringify(), followed by string.replace() on the resulting string to make updates to both keys a ...

Retrieve the value of an object without relying on hardcoded index values in TypeScript

I am working with an object structure retrieved from an API response. I need to extract various attributes from the data, which is nested within another object. Can someone assist me in achieving this in a cleaner way without relying on hardcoded indices? ...

Exploring the combined application of the AND and OR operators in JavaScript programming

{Object.keys(groupByMonthApplicants).map((obj,i) => <div key={obj} style={(i > 0 && (this.state.selectedTabId !== 'rejected' || this.state.selectedTabId !== 'approved')) ? {paddingTop:'15px',background:&a ...