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:

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

Is there a JavaScript method for opening a new window regardless of the PHP file being used?

I have encountered a small dilemma that is causing me frustration. Currently, I have set up a BUTTON on my website. This button, when clicked, triggers a JavaScript function to open a "New Window". The code for this button and function looks like this : ...

Node.js publication date displaying incorrectly

When I post a date to elasticsearch, I typically use Date.now() var unixtime = Date.now(); The output usually looks something like this: 1373508091156 To convert it, I then use the following code: var date = new Date(unixtime*1000); After conversion, ...

Tips for preserving the status of a sidebar

As I work on developing my first web application, I am faced with a navigation challenge involving two menu options: Navbar Sidebar When using the navbar to navigate within my application, I tend to hide the sidebar. However, every ti ...

Unlock exclusive design features from beyond a Component's borders (NativeScript + Vue)

My application is made up of: 6 different components within the component folder, 3 JavaScript files located in the library folder. Within component_1, there is a Layout with a reference called myLayout. One of the JS files, myLayoutHandler, manipulates ...

Sort and incorporate elements by multiple strings present in an array

Looking to filter and include strings in an array by matching them with items in another array? Here is a sample code snippet that filters based on a single string: const filteredString = `${this.filter}`.toLowerCase(); this.filteredCampaigns = this. ...

Save an array of messages by making separate API calls for each one

I have a function that makes an API call to retrieve a list of message IDs. Here is the code: function getMessageList(auth) { api.users.messages.list({ auth: auth, userId: 'me', }, function(err, response) { if (er ...

What factors contribute to the poorer performance of SVG rendering compared to PNG rendering?

I conducted a comparison of two images across various browsers. One image is an SVG while the other is a PNG format. Here are my findings: You can view the demo on JSFiddle here: http://jsfiddle.net/confile/2LL5M/ This is the code snippet I utilized: ...

Delay the execution of the function in AngularJS until the browser has finished rendering completely and the view-model synchronization cycle has ended

I'm uncertain about the appropriate title for this inquiry, so please correct me if I am mistaken. Suppose that upon page refresh (load), I require an animated scroll to an anchor based on the current location's hash (I am aware of ngAnchorScrol ...

Inject nested controller dynamically

I am working on a straightforward ASP.NET MVC application that includes an ng-controller. I am trying to inject another ng-controller inside this controller using a partial view, but I'm having trouble getting the binding to work correctly. You can s ...

I am noticing that my popover is causing my page to shift when I click it. It is expanding the width of my page more than I would

Upon clicking the user id popover on my page, it expands the page width instead of adjusting within the page boundaries. This is the issue: https://i.stack.imgur.com/EqaMo.png There's a small white space present that I want to eliminate. When the po ...

Is there a way to find the JavaScript Window ID for my current window in order to utilize it with the select_window() function in

I'm currently attempting to choose a recently opened window while utilizing Selenium, and the select_window() method necessitates its WindowID. Although I have explored using the window's title as recommended by other sources, and enabled Seleni ...

How can we display the Recent Updates from our LinkedIn profile on our website using iframe or javascript?

Currently, I am in the process of developing a .NET web application for our company's website. We already maintain an active LinkedIn profile where we regularly post updates. https://i.stack.imgur.com/T2ziX.png My main query at this point is whether ...

Creating stunning visuals with the power of SVG

I need to create a graphics editor similar to Paint using SVG for a school project. I have JavaScript code for drawing shapes like circles and lines, but when I try to add them to an onClick function for a button, it doesn't seem to be working. funct ...

Unable to retrieve input using jquery selector

I am attempting to detect the click event on a checkbox. The Xpath for the element provided by firebug is as follows, starting with a table tag in my JSP (i.e. the table is within a div). /html/body/div[1]/div/div/div[2]/div/div[2]/div[1]/div/div[2]/table ...

Utilize Haxe Macros to swap out the term "function" with "async function."

When I convert haxe to JavaScript, I need to make its methods asynchronous. Here is the original Haxe code: @:expose class Main implements IAsync { static function main() { trace("test"); } static function testAwait() { ...

The application freeze is being caused by the Lodash isEqual function

While developing a React component, I have set the default export as shown below: React.memo(MyReactComponent, isEqual) The isEqual function used here is from the lodash library. The issue I am facing is that my application tries to update the component ...

Is there a way for me to gain entry to this array in vuejs?

Can anyone help me with accessing the objects in this array? I am using laravel, inertiajs, and vuejs. I am passing a variable from a laravel controller to a vuejs component with inertia.js. https://i.stack.imgur.com/p7yjL.png https://i.stack.imgur.com/y ...

Typescript encounters ERROR TS1128: Expecting a declaration or statement

Having trouble with a TypeScript error in my game-details.component.ts file that I've been trying to fix for a couple of hours. It's showing up at line 26, column 54 and everything seems correct to me. Interestingly, when I press CTRL + S in my ...

Obtain the user's email using nodemailer

I created a contact form using Nodemailer that I am having trouble with. Take a look at the code below: let mailOptions = { from: '<<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e3636360e363636602d2123">[emai ...

What is the time stamp format of 1651928421543667000?

Recently, I have encountered an issue with an API returning a timestamp as 1651928421543667000. Despite trying various PHP functions like strtotime(), datetime(), and strftime(), I am unable to find the correct format for it. Can anyone provide some guid ...