How can I extract URL parameters in Vue.js using a JavaScript file?

Currently, I have a URL: http://local-pr.local?id=12

Within the file page.vue:

  • Upon using:
    console.log(this.$route.query.id)
    , I successfully retrieve the value.

Now, my objective is to access this parameter in the file: page.js

import addon from './addon'
import user from './user'

// My intention is to verify if there is a new 'id' parameter that needs to be exported.
if (this.$route.query.id) {
   export default [...addon, ...user]
}
  • console.log(this.$route.query.id)

However, an ERROR occurs: Reason: TypeError: Cannot read properties of undefined (reading '$route')

I am seeking guidance on how to retrieve parameters in a JavaScript file. Any insights or experiences would be greatly appreciated. Thank you!

Answer №1

One way to approach this is by creating a function that accepts the $route as an argument:


import addon from './addon'
import user from './user'

export default function checkParams(route) {
   if(this.$route.query.id){
    return [...addon, ...user]
  }
}

Then, you can use this function in any component like so:

import checkParams from './page.js'

.....

let data = checkParams(this.$route)

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

Attempting to create a fresh string by substituting certain characters with different ones

Exploring TypeScript, I encountered a puzzle where I needed to substitute specific characters in a string with other characters. Essentially, replacing A with T, T with A, C with G, and G with C. The initial code snippet provided to me looked like this: e ...

Tips for creating a countdown timer from scratch without relying on a plugin

Looking at this image, it is clear that jQuery can be used. However, I am wondering if there is a way to create a countdown timer without relying on plugins. Can anyone offer some guidance? ...

Leverage the power of jQuery to manipulate video tags

Here's the challenge: I need to utilize a jQuery function to extract a URL from a link's REL attribute and then transfer it to a video element. The extraction process and transmission seem to be working smoothly. However, my struggle lies in act ...

Is it possible to duplicate native functions in JavaScript, such as window.alert or document.write?

I am looking to replace all instances of the alert function in my code with a custom alert message saying "you used alert". var hardCodedAlert = alert; //Although I understand this won't work. What other approach can I take? window.alert=function(){ ...

Troubleshooting a Basic jQuery Validation Problem

I've been attempting to incorporate the "Refactoring rules" segment from http://jqueryvalidation.org/reference/ However, I'm struggling to figure out the appropriate placement for the $.validator code. Currently, I'm inserting it like this: ...

To ensure that checkboxes are automatically checked in AngularJS 1.5, the model should be bound to the objects without using the ng-checked

Due to various conflicts and dependencies, I have opted to use AngularJS 1.5.x instead of 1.6.x, which has led me to encounter some issues with ng-checked functionality. Within my ng-repeat loop, I am dealing with 2 objects: vm.stateList, containing all ...

React: Dynamic input field that removes default value as the user begins typing

Imagine a scenario where we have a text box in a React application with Formik and Material UI that accepts a price as a floating point number. By default, the field is set to 0. However, once the user manually enters a number, the default value should be ...

Understanding the grammar of the Web Speech API

Could someone please explain the meaning of this code snippet? const grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghost | white | g ...

Trouble with component not refreshing upon store modification in Vuex

Summary: If you prefer, I have a video detailing my issue: https://youtu.be/Qf9Q4zIaox8 Concern with Navbar Component Not Updating on Store Change. The issue I'm facing involves the Navbar component not updating when there is a change in the store. ...

Encountering an issue while implementing a fresh design using Material-UI Version 5 and React Version 18.01 - Specifically facing problems with the '@mui/styles' package

Hi there! I am currently working with react V.18.01 and Material-ui v.5 for my application development, but encountered an error that I need assistance with. Being a beginner developer, I would greatly appreciate a code review to help me understand the iss ...

Material-UI: Error - getMuiTheme function is not defined

After recently updating my material-ui to version 0.15.4, I encountered an issue while trying to make it work. The error message states that getMuiTheme is not a function, despite the fact that the relevant JavaScript file is present in the folder location ...

Experiencing an unusual issue with grunt: The Gruntfile.js seems to be missing the 'flatten' method

Encountering an unusual error message while attempting to run grunt stated: TypeError: Object Gruntfile.js has no method 'flatten' Being a beginner with node.js, npm, and grunt, I believe my installation of node, npm, and grunt was done correctl ...

Using the getAttribute method in Edge with JavaScript

My goal is to dynamically load videos on the page after it has fully loaded. I have a script that successfully works in Firefox and Chrome, but I encounter errors when using Edge/IE. The specific error message I receive is SCRIPT5007: Unable to get propert ...

Insert a hyperlink button using InnerHtml

I am facing an issue with displaying a list item that contains a tab and a link button: <li runat="server" id="liActivityInvoices"><a href="#tabActivityInvoices">Invoices</a><asp:LinkButton runat="server" ID="btnLoadInvoice" OnClick=" ...

Updating a component property value through the template

Consider the code snippet below: import { Component, OnInit,Input } from '@angular/core'; @Component({ selector: 'topic-details', templateUrl: './detailpane.component.html', styleUrls: ['./detailpane.component.scs ...

Identify when a div reaches the end of the screen using CSS

I've developed a custom dropdown feature using Vue 2 and TypeScript to meet our specific requirements (without relying on jQuery). The dropdown functions correctly, opening the options list downwards when the main box is clicked. One enhancement I a ...

Fundamental modeling using Node.js with Mongoose

Currently, I am facing a challenge with developing a node.js application. My goal is to create a model for a musical scale that includes a name and a set of associated notes: var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ...

The black package in package-lock.json seems to have a mind of its own, constantly disappearing and re

When running npm install, I've noticed that the property packages[""].name in the package-lock.json file is sometimes removed and sometimes added. How can I prevent this change from occurring, as it is causing unnecessary git changes? https ...

Reveal and Conceal, the ever-changing show

As I work on my blog, I want to make the layout more compact by having a link that reveals comments and entry forms when clicked. I've seen this feature on other sites as "Comments (5)", but I'm unsure how to implement it myself. Below is a snip ...

Parse a string and generate an array using regular expressions in JavaScript/Node.js

I'm currently working on coding in JavaScript to extract an array of elements after splitting using a regular expression. var data = "ABCXYZ88"; var regexp = "([A-Z]{3})([A-Z]{3}d{2})"; console.log(data.split(regexp)); The current output is [ &a ...