The $route object in vue-router appears to be empty when used with single file components

I am facing an issue while using single file components with vue-router and vue-2.0. The problem I can't seem to resolve is that the this.$route object, when called from a component, always returns empty values.

For example:

https://i.sstatic.net/wsUct.png

Messages.vue

<template>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Post List</div>

                    <div class="panel-body">
                        <li v-for="item in items">
                            {{ item.message }}
                        </li>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        created() {
            console.log(this.$route);
        },
        mounted() {
            console.log('Component mounted.')
        },
        data() {
            return {
                items: [
                    {message: 'Foo'},
                    {message: 'Bar'}
                ]
            }
        },
    }
</script>

App.js

import Vue from 'vue';
import VueRouter from 'vue-router';
import Messages from './components/Messages';

Vue.use(VueRouter);

const routes = [
    { path: '/user/get/:id', component: Messages},
]

const router = new VueRouter({
    routes
})

const app = new Vue({
    router,
    el: '#app',
    components: { Messages }
});

Your assistance on this matter would be highly appreciated.

Answer №1

To instruct Vue to display the router views, you simply need to make a small adjustment in the Vue initialization process. Just add a template that includes the route-view directive.

const app = new Vue({
  router,
  el: '#app',
  template: '<router-view/>',
  components: { Messages }
})

This tweak should enable it to function as expected.

Answer №2

Without the accompanying HTML code representing the template used by the root component for rendering, it becomes challenging to pinpoint the exact issue.

If your root component renders a router-view component, then the route parameters should be accessible in the Messages instance.

For reference, you can check out an example based on your configuration here: https://codepen.io/autumnwoodberry/pen/WEBEKd?editors=1010

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

Generating interactive elements in VUE is key

I am unsure about how to dynamically create components without using the <component :is=''> tag. I would like to insert a component into the DOM through JavaScript. Similar to how you would add a new modal in jQuery with $("body").append(" ...

What is the reason for the absence of the $.ajax function in the jQuery package designed for node.js?

Here is my code sample, which I would like to use for practicing with jQuery's ajax function. Note that I have already installed the jQuery package using npm install jquery: var $ = require('jquery'); var remoteValue = false; var doSometh ...

What are some ways to troubleshoot the UI of a Nativescript app?

As a newcomer to NativeScript technology, I often encounter challenges while developing applications. Whether it's troubleshooting why a textview is not displaying properly, identifying layout overlaps, or detecting other distortions in the UI, debugg ...

Angular Bootstrap's tabs feature a powerful select() function that allows users to easily

Take a look at this where you can find a tab component. Within the tab settings, there are methods like: select() and deselect() I was unsure how to properly utilize them. I attempted to access them from my JavaScript file using $scope but encountered ...

What is the best way to insert a new row into a table upon clicking a button with Javascript?

Hi everyone, I'm facing an issue with my code. Whenever I click on "Add Product", I want a new row with the same fields to be added. However, it's not working as expected when I run the code. Below is the HTML: <table class="table" id="conci ...

Enforce directory organization and file naming conventions within a git repository by leveraging eslint

How can I enforce a specific naming structure for folders and subfolders? I not only want to control the styling of the names (kebab, camel), but also the actual names of the folders and files themselves. For example, consider the following paths: ./src/ ...

How to connect site pages in WordPress using Vue.js

I'm currently in the process of revamping a website using the vuejs framework and I've started off with this boilerplate as my foundation. My experience with vuejs is very fresh, just 3 days old, so I'm still trying to understand how to crea ...

Steps to create two jQuery dropdown filters for multiple identifiers:

Is it possible to create two dropdown menus that can be used to filter a gallery of images? I am currently facing an issue where the filtering functionality is not working after adding a name attribute to the image IDs. When I select an option from the s ...

Making an asynchronous request from jQuery to a Slim Framework API endpoint

I'm currently working on incorporating Slim into my project and I'm facing some challenges with setting up the AJAX call correctly: $.ajax({ url: "/api/addresses/", type: 'POST', contentType: 'application/j ...

Why is my jQuery blur function failing to execute?

Currently, I am working with HTML and the jQuery library to avoid core JavaScript in order to maintain consistency. In my project, there are 3 fields and when a user clicks on field1 and then somewhere else, I want only field1's border to turn red. T ...

Send the 'key' parameter to the React component

Attempting to pass a parameter named "key" to a react component is resulting in it not functioning properly. However, when I use "keyy" instead of "key," it works as intended. It appears that using "key" as a parameter name may be causing issues due to it ...

Interconnected props in Material UI components interact with one another

Is there a way to have the value of one property in a Material UI component reference another property within the same component? For example, can I make the value property in a Switch component refer to the checked property? <Switch checked={sing ...

Cypress and Cucumber collaborate to reinitialize the requests within Next Js

In my upcoming project with Next.js, I am utilizing Cypress for testing a specific page. The objective is to validate two scenarios: 1. Successful outcome and 2. Error handling when a user encounters an issue. Before(() => { return void cy.server() ...

Fetching data from the server using Angular and parsing it as JSON

Can anyone provide some insight on the best way to use jsonObjects in ng repeat? Here is my code: This is the response I get from PHP: die(json_encode(array('sts'=>'success', 'title'=>'*****', 'msg' ...

What is the best way to enable my search function to filter out specific items from a table?

Currently, I have created a table populated with data fetched from a JSON file. Now, my focus is on implementing a search functionality that filters out items based on user input and displays only those table rows matching the search criteria. The code sni ...

The Bootstrap navigation pills do not function properly when using a forward slash in the tab link

I am currently working with Bootstrap and using nav pills. I have noticed that if I include a / sign in the link of a tab, it causes that specific tab to malfunction and triggers a JavaScript error in jQuery's own code when clicked on. How can I go ab ...

The JavaScript exec() RegExp method retrieves a single item

Possible Duplicate: Question about regex exec returning only the first match "x1y2z3".replace(/[0-9]/g,"a") This code snippet returns "xayaza" as expected. /[0-9]/g.exec("x1y2z3") However, it only returns an array containing one item: ["1"]. S ...

Is there a way to use ng-click to switch the ng-src of one image with that of another?

*I made updates to the plunkr and code to reflect my localhost version more accurately. It turned out that the AngularJS version was not the issue even after fixing the previous plunkr.* Let me start by saying that I am facing some challenges with Angular ...

Creating a code script for the purpose of automating npm commands

Currently, I am immersed in an angular js project and I have a desire to streamline the execution of the following two commands. ./node_modules/protractor/bin/webdriver-manager update ./node_modules/protractor/bin/webdriver-manager start The challenge li ...

In a React application, the input field unexpectedly loses focus after typing just one character

Has anyone encountered an issue with a dropdown menu causing input field focus to be lost after typing one character? I've attempted setting unique keys for each field, but it hasn't resolved the problem. For reference, here is the link to the p ...