The Vue.js 2 router is exclusively pulling components from the navigation bar, rather than directly from the URL

After selecting a page from the menu, the correct component loads. However, directly accessing the page URL does not display the content.

This is the main template (which contains the menu):

<template>
    <div class="row">
        <div class="col-md-3 col-sm-3 col-xs-3">
            <router-link to="/new-page" type="button" class="btn btn-primary btn-lg btn-block">New page</router-link>
            <div class="list-group sidebar">
                <router-link v-for="page in pages" class="list-group-item" :to="'/pages/' + page.slug">{{ page.menu_title }}</router-link>
            </div>
        </div>
        <div class="col-md-9 col-sm-9 col-xs-9">
            <router-view></router-view>
        </div>
    </div>
</template>

<script>
    export default {
        computed: {
            pages() {
                return this.$store.state.pages
            }
        },
        created() {
            this.$http.get('pages').then((response) => {
                this.$store.commit('setPages', response.body)
                console.log(response)
            }, (response) => {
                console.log("Error: " + response)
            })
        }
    }
</script>

This is the section responsible for loading different types of content based on the selected page. It dynamically updates with the corresponding data:

<template>
    <div>
        <div class="loader" v-if="loading">
            <div class="bounce1"></div>
            <div class="bounce2"></div>
            <div class="bounce3"></div>
        </div>
        <div v-if="!loading">
            <vc-gig :content="content" v-if="content.type == 'gig'"></vc-gig>
            <vc-news :content="content" v-if="content.type == 'news'"></vc-news>
            <vc-home :content="content" v-if="content.type == 'home'"></vc-home>
            <vc-image :content="content" v-if="content.type == 'image'"></vc-image>
        </div>
    </div>
</template>

<script>
    import Gig from '../Gig.vue'
    import News from '../News.vue'
    import Home from '../Home.vue'

    export default {
        components: {
            'vc-gig': Gig,
            'vc-news': News,
            'vc-home': Home,
        },
        data() {
            return {
                loading: true,
                content: [],
            }
        },
        created() {
            this.getPageData
        },
        watch: {
            '$route': 'getPageData'
        },
        methods: {
            getPageData() {
                this.loading = true

                this.$http.get('pages/' + this.$route.params.pageSlug).then((response) => {
                    this.content = response.body
                    this.loading = false
                    console.log(response.body)
                }, (response) => {
                    console.log(response)
                })
            }
        }
    }
</script>

Although all components load correctly when accessed through the menu, they fail to load when manually entering the URL in the browser.

Update: Below is my complete routes.js file:

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

// various imports...

Vue.use(VueRouter)

const Router = new VueRouter({
    mode: 'history',
    routes: [
        // route configurations...
    ]
})

Router.beforeEach(function (to, from, next) {

    // Authenticated user redirect
    if (to.matched.some(function (record) {
            return record.meta.guest
        }) && Vue.auth.loggedIn()) {
        next({
            path: '/pages'
        })
    } else {
        next()
    }

    // Unauthenticated user redirect
    if (to.matched.some(function (record) {
            return record.meta.auth
        }) && !Vue.auth.loggedIn()) {
        next({
            path: '/login'
        })
    } else {
        next()
    }
})

export default Router

Answer №1

A quick solution is to remember to execute the method you have created.

created() {
     this.getPageData
},

Instead, it should be:

created() {
  this.getPageData()
},

It may also be beneficial to use a linter like eslint to catch these types of errors before they happen.

http://eslint.org/

Enjoy your coding session!

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

Tips on how to show the image icon in place of the image name

Here is a code snippet for multiuploading images using Vue. Currently, the uploaded images are displayed by their file names. However, I am looking to enhance this functionality by displaying an image icon instead of the file name. If anyone knows how to ...

Locate the indices of several maximum values within an array

Here is an array for reference: var exampleArray = [10, 67, 100, 100]; The goal is to identify the indexes of the maximum values in the array. The existing function currently locates only one index: function findMaxIndexes(arr) { var max = arr[0] ...

Angular fails to refresh Ng-class after on-change event is activated

Encountering an unusual issue with Angular. While I can trigger the desired action with ng-click, I must utilize onchange for other specific requirements. Although my code works smoothly for other buttons that execute the same action, the upload button fa ...

Error 404: Node.js and Express encountering issues with POST request to '/webhook' endpoint

https://i.sstatic.net/CTDCv.pnghttps://i.sstatic.net/KjPeC.pngI've encountered a peculiar issue where I keep receiving a 404 error specifically when sending a post request to '/webhook'. This error is persistent even though the rest of my po ...

What is the best way to position a div below a sticky navbar?

I have implemented a sticky navbar on my index page along with JavaScript code that adjusts the navbar position based on screen height. When scrolling, the navbar sticks to the top of the page, but the flipping cube overlaps with the sticky navbar. How can ...

The CheckboxTable component in material UI fails to update when there is a change in props

As I develop an admin system, one of the key features I want to implement is the ability to display a list of users in a table format. Additionally, I want to enable bulk actions such as delete and update flags, along with pagination. <CheckboxTable ...

It is not possible to utilize Vue.js to employ the <slot> feature for rendering the parent component

After attempting to implement the slot feature following the example on the Vue official site, I encountered a failure despite keeping my code very concise. Parent Component <template> <subMenuTemp> <div class="text" > paren ...

The React getTime() method does not properly update the state

I am attempting to update the state of the component Demoss using an external function called getTime(). My goal is to start updating the time in the state time when the page loads. In order to achieve this, I have called it in the componentDidMount meth ...

Mastering the art of tab scrolling in VueJS using Bootstrap-vue

Currently, I am working on a VueJS project that utilizes bootstrap-vue. The issue I am facing is that when rendering a list of tabs, it exceeds the width of its parent container. To address this problem, I aim to implement a solution involving a set of but ...

Utilizing ID's within a jade template embedded within a P HTML element

Using the jade template, I successfully formed this paragraph. My next step is to add an ID or a class around the word stackoverflow. How can I achieve this in jade? I am aware that in regular HTML we would use something like <div class="className"> ...

What is the mechanism behind image pasting in Firefox's imgur integration?

Start by launching an image editing software and make a copy of any desired image. Avoid copying directly from a web browser as I will explain the reason later on. Navigate to "http://imgur.com" using Firefox. To paste the copied image, simply press Ctrl+V ...

What is the best way to generate a ul-li structure using JSON input and jQuery?

There is a JSON variable present: var links=[{"text":"Home","href":"http://home.com","icon":"fas fa-home","target":"_top","title":"My Home","children":[{"text":"home2","href":"home2.com","icon":"fas fa-chart-bar","target":"_self","title":"home2","category ...

Determine the total hours and minutes elapsed between two specific dates and times

Looking for some assistance here. I have a form where users need to input a start time and end time of an incident. After entering this information, they would manually calculate the duration between the two date times. I am attempting to streamline this p ...

The sorting functionality in Angular.js using the orderBy directive seems to be malfunctioning as it is not

Within this code snippet, @Model.jsonString represents a string. @model WebApplication1.Models.Car @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <html> ... <body ng-app="myModule"> <div ng-controller="myC ...

When utilizing the dispatch function with UseReducer, an unexpected error is triggered: Anticipated 0 arguments were provided,

Having trouble finding a relevant answer, the only one I came across was related to Redux directly. So here's my question that might be obvious to some of you. In my code, everything appears to be correct but I'm facing an error that says: Expect ...

When I log them out, Node.js express always manages to bail me out even when Object is not defined

While attempting to destructure an object in my express middleware: const verifyLoggedInStatus = (req, res, next) => { try { const token = req.cookies['jwt-auth'].token; console.log('token: ', token); req. ...

Searching for single and double quotes within a string using RegExp in JavaScript

I have encountered an issue while searching for a substring within a string using the code below: mystring.search(new RegExp(substring, 'i')) The reason I am utilizing new RegExp is to perform a case-insensitive search. However, when the string ...

The require statement in Vue.js is failing to function dynamically

Having trouble dynamically requiring an image in Vue.js and it's not functioning as expected <div class="card" :style="{ background: 'url(' + require(image) + ')',}"> export default { data() { return { ...

Encountering Errors with Angular JS Following Update from Version 1.1.0 to 1.1.1

After upgrading, I noticed that the ng-repeat function is taking significantly longer to load and is attempting to display additional content boxes without serving the actual content provided by $resource. I have pinpointed the issue to the update from ve ...

Deselect the checkbox that was initially selected when an alternative checkbox option has been chosen

I am trying to implement a feature where there are 2 groups of checkbox options on the same page. Below is the code snippet: <div class="col-xs-12"> <label class="checkbox-inline"> <input type="checkbox" th:field="*{borrowerRace1}" th:val ...