When using a Vue.js component, the value of this.$route can sometimes come back

I am attempting to retrieve the parameters from the URL and pass them into a method within a Vue component.

Despite following advice to use this.$route, I am consistently getting an 'undefined' response. I have tried various solutions suggested by others with similar issues, but none seem to work for me.

<template>
  {{ this.$route.query }}
</template>

<script>
  export default {
    name: 'cards',
    data: () => ({
      items: [
        {
          id: 1,
          title: '8 myths about mobile interfaces',
          link: 'https://medium.muz.li/8-myths-about-mobile-interfaces-390d9e2cee33',
          folder: 'medium',
          order: 1,
        },
        {
          id: 2,
          title: 'Asking your user’s gender, the new skeuomorphism, upside-down UIs and more',
          link: 'https://uxdesign.cc/asking-your-users-gender-the-new-skeuomorphism-upside-down-uis-and-more-e108ef888030',
          folder: 'medium',
          order: 2,
        },
      ],
    }),
    methods: {
      link: () => {
        console.log(this.$routes.query);
      },
    },
  };
</script>

Using this.$route in the template displays correct information, but I am unsure how to display the parameters.

My understanding of Vue is still developing, and there may be a better approach to achieving my goal of displaying folder content based on the URL parameter. Any suggestions are welcome!

If you can identify why the route is not displaying, please let me know. Additionally, here is my Vue router file for reference:

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

import cards from './cards/cards';

Vue.use(VueRouter);

export default new VueRouter({
  routes: [
    {
      path: '/cards',
      name: 'cards',
      component: cards,
    },
  ],
  mode: 'history',
});

Answer №1

If you want to access this, it is recommended not to use arrow functions. Regular functions should be used instead:

methods: {
  links: function() {
    console.log(this.$route) // this should work
  }
}

This information can also be found in the Vue documentation, such as in this note at the bottom of https://v2.vuejs.org/v2/api/#data.

Answer №2

Utilize the object definition method shorthand to achieve a similar outcome as explained in Egor Stambakio's response, but with fewer characters, hooray!

methods: {
  links() {
    console.log(this.$route) // should still function properly
  }
}

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

Techniques for accessing the most recent input values within a loop

Here is the HTML code snippet: <div v-for="item in my_items"> <div> <input type="text" :value=item.name /> </div> <div> <button @click="edit(item.id, item.name)">Edit ...

Find your favorite artist on Spotify through the search function

Recently, I stumbled upon this intriguing demo showcasing how to search for an artist using the Spotify API. However, despite several attempts, I have been unable to make it function properly. Can anyone provide any tips or guidance on making this work suc ...

Creating an IntersectionObserver with the Composition API: A Step-by-Step Guide

I am currently in the process of incorporating an IntersectionOberver that will update the url once the viewport transitions into a new section. I came across This thread and now endeavoring to apply it in vue 3 compositon api. The script is being integra ...

Troubleshooting issues with filtering two MongoDB arrays in ES6 and finding a solution

I have a scenario where I am requesting two arrays of objectIDs from MongoDB, and then attempting to identify the differences between the two arrays. In addition, I am passing these arrays through express middleware using res.locals. Below is the code sn ...

In the process of developing a custom Vue component library with the help of Rollup and VueJS 3

My goal is to develop a custom Vue component library using rollup and Vue.js. The process went smoothly with Vue2, but I encountered issues parsing CSS files with Vue3. To address this, I updated the dependencies in the package.json file. package.json { ...

I'm trying to determine in Stencil JS if a button has been clicked in a separate component within a different class. Can anyone assist

I've created a component named button.tsx, which contains a function that performs specific tasks when the button is clicked. The function this.saveSearch triggers the saveSearch() function. button.tsx {((this.test1) || this.selectedExistingId) && ...

Vue app setup interrupted by miscellaneous ECONNRESET warning

While setting up my vue app using vue-cli, everything went smoothly until I ran the command npm install to install dependencies. I encountered an error with https, so I switched it to http which resulted in the following log: npm WARN registry Unexpecte ...

Transform PHP array into a JavaScript array

Currently, I am using Laravel and retrieving a list of values from a database with the following code: $idordenes = DB::table('ordenes')->select('id')->get(); Upon echoing the idordenes variable, the output is as follows: [{"fa ...

"Learn how to easily send media files stored on your local server via WhatsApp using Twilio with Node.js and Express

Whenever I attempt to send the PDF file created through WhatsApp, an error pops up preventing me from viewing it. easyinvoice.createInvoice(data, function(result) { //The response will contain a base64 encoded PDF file ...

Randomizing jQuery for duplicated HTML/jQuery elements

I'm facing a challenge with my jQuery and HTML scripts. I have a dropdown menu where a randomly generated number is displayed in the supplies field (voorraad) based on the selected option. However, when I clone this field using the add button, the fun ...

Is there a way to insert a secured page right before accessing the dashboard?

I am trying to create a locked page that will display a message when users access the web app from a mobile device and load a mobile layout page displaying a message like mobile is not supported. I was considering using document.addEventListener('DOMC ...

The regex pattern did not match the line of code in the Node.js script

I need help finding a regex pattern that can identify any line of code containing just one reference to a core module. Here is an example: const coreModuleMatches = /'^[var|const]{0,1}[a-z\$\_]{1,}=require([\'|"][assert|fs|path][ ...

By pairing delay(0) with refCount(), we can achieve optimal efficiency

The refCount operator is discussed in this article. It explains the necessity of adding delay(0) to prevent unsubscription of observable A: import { Observable } from "rxjs/Observable"; const source = Observable.defer(() => Observable. ...

Can two different versions of ReactJS run simultaneously on a single page?

Hey everyone, I'm curious if it's possible to have two different versions of ReactJS running on the same page, similar to how jQuery has jQuery.noConflict(). After doing some research, I came across some interesting findings: Two Reacts Won’t B ...

Utilizing a Jquery plugin for enhanced form validation with the inclusion of supplementary techniques

I am looking to integrate a jQuery plugin into my form validation process, specifically to ensure that only letters are allowed in the name section. If a user enters special characters or numbers, I want the form to display an error message. Additionally, ...

The fixed positioned div with jQuery disappears when scrolling in Firefox but functions properly in Chrome, IE, and Safari

Click here to see a div located at the bottom of the right sidebar that is supposed to behave as follows: As you scroll down the page, the div should change its class and become fixed at the top of the screen until you reach the bottom of the parent el ...

Assistance needed in obtaining the ID of a specific table row using jQuery

Currently, I am working on an AJAX request using Jquery and PHP. The task involves looping through an array to generate a table. During each iteration, a new ID is assigned to the table row. When users click on the "read me" link, additional content is f ...

Occasionally, AJAX requests may not always be in the correct sequence

I'm struggling with the POST and GET requests. Everything seems to be in order on my server side until I send the data, but then things get jumbled up on the client side. For instance, the data should be received in reverse order as shown below: Data ...

How can I show/hide a div based on checkbox click on my website? It works in jsFiddle, but not on my actual site. Any suggestions?

Is there a way to show or hide a div based on a checkbox click? I've got it working in jsFiddle, but for some reason, it's not functioning properly on my website. Any thoughts on how to fix this? My goal is to offer multiple payment methods (cre ...

Adding HTML attributes to a VueJS table allows for more customization and control

Is it possible to incorporate HTML/Bootstrap elements into a cell in VueJS? <b-table striped show-empty :items="filtered"> <template slot="top-row" slot-scope="{ fields }"> <td v-for="field in fields& ...