The beforeRouteUpdate hook in vue-router is unable to access the `this` keyword

I am currently creating a Vue.js application with vue-router.

According to the documentation, within the hook beforeRouteUpdate, I have full access to the component using the keyword this:

The documentation mentions that beforeRouteEnter is the only guard that allows passing a callback to next. For beforeRouteUpdate and beforeRouteLeave, this functionality is already available, so passing a callback is not necessary and therefore not supported:

Thus, I implemented the following code snippet:

    ...
    methods: {
      ...mapActions({
        setFileDetails: 'setFileDetails',
        setActionParams: 'setActionParams',
        setSelectedFileId: 'setSelectedFileId',
      }),
      goToImportSource() {
        this.$router.push('/import');
      },
      openAnnotationsView(item) {
        this.$router.push(`/ingestion/queue/${item.id}`);
      },
    },
    beforeRouteUpdate: (
      to,
      from,
      next,
    ) => {
      this.setSelectedFileId(to.params.id);
      next();
    },
  };
</script>

However, upon implementing this code, I encountered the following error:

vue-router.esm.js?fe87:16 [vue-router] uncaught error during route navigation:

TypeError: _this.setSelectedFileId is not a function
    at VueComponent.beforeRouteUpdate (PageIngestionQueue.vue?3869:67)
    at boundRouteGuard (vue-router.esm.js?fe87:2080)
    at iterator (vue-router.esm.js?fe87:1943)
    at step (vue-router.esm.js?fe87:1717)
    at step (vue-router.esm.js?fe87:1721)
    at step (vue-router.esm.js?fe87:1721)
    at step (vue-router.esm.js?fe87:1721)
    at eval (vue-router.esm.js?fe87:1718)
    at eval (vue-router.esm.js?fe87:1964)
    at eval (routeRules.js?b464:9)

If I call this.setSelectedFileId elsewhere in the component, it functions correctly...what could be causing this issue?

Answer №1

It is recommended to use the function() {} syntax instead of the () => {} syntax in this specific scenario, as the latter will bind this:

beforeRouteUpdate(to, from, next) {
  this.setSelectedFileId(to.params.id);
  next();
}

Alternatively, you can also use:

beforeRouteUpdate: function(to, from, next) {
  this.setSelectedFileId(to.params.id);
  next();
}

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

The ideal method to transmit reactive data effectively is through Vue.js

Implementing vue.js. I've created an authentication file (auth.js) that stores the user information upon detecting a change in authentication state. There are other sections of the website that need to update when the user information changes. What is ...

JS/Apps Script: Passing object and its keys as function parameters

When working with Google Apps Script, I have a specific task that involves looping through data and writing only certain keys to a sheet. I want this looping operation to be done in a separate function rather than directly in the main function, as it will ...

Each time the page is refreshed, the most recent form data submitted is continually appended to an array

I have implemented a post request to add input data from a form. The entered data is stored in an array variable burg and then displayed on my index.handlebars view. Everything works as intended, but when the page is refreshed without any input in the form ...

Conceal a different CSS class if a certain CSS class is present on the page

I am currently working on organizing my page to distinguish between purchased and unsold products. For the items that have been bought, I am using the CSS class "winning_bid" within a div element. My goal is to hide another div with the class "price" if th ...

Divide the sentence using unique symbols to break it into individual words, while also maintaining

Is there a way to split a sentence with special characters into words while keeping the spaces? For example: "la sílaba tónica es la penúltima".split(...regex...) to: ["la ", "sílaba ", "tónica ", "es ", "la ", "penúltima"] ↑ ...

Creating Interactive Graphs with HTML and JavaScript: A Guide to Dynamic Graph Drawing

I am seeking to create a dynamic graph using standard HTML, JavaScript, and jQuery (excluding HTML5). The nodes will be represented by divs with specific contents, connected by lines such as horizontal and vertical. The ability to add and remove nodes dyn ...

I'm having trouble getting my Ajax edit code to function correctly. Can anyone offer some assistance?

I am currently working on a basic registration system that includes two forms: one for registration and another for selecting a city. I have encountered an issue where newly added cities update perfectly, but when trying to use the selected city in the reg ...

"Enjoy a unique browsing experience with a two-panel layout featuring a fixed right panel that appears after scrolling

I am facing difficulty in designing a layout with two panels where the left panel has relative positioning and the right panel becomes fixed only after a specific scroll point. Additionally, I need the height of the right panel to adjust when the page scro ...

Supertest and Jest do not allow for sending JSON payloads between requests

Below is the test function I have written: describe("Test to Create a Problem", () => { describe("Create a problem with valid input data", () => { it("Should successfully create a problem", async () => { const ProblemData = { ...

Checking the validity of a JSON file extension using regular expressions

Using EXTJS, I have created a file upload component for uploading files from computer. I need to restrict the uploads to JSON files only and want to display an error for any other file types. Currently, I am able to capture the filename of the imported fil ...

Hyphens make Tablesorter sort numeric fields uniquely

I have a table where data is displayed in the format of YYYY-####. Sometimes, there are values like 2012-456 and 2012-1234. By default, the sorting places 2012-1234 before 2012-456. If I change the sort to 'numeric', it disrupts the order of othe ...

Tips for adjusting the minimum attribute within an input field with jQuery

In my form, I have an input field with arrows (up and down). Next to it, there are two buttons: + and -. When I click on the input field and then use the arrow, the system retrieves the value from a dropdown list, which works fine. However, when I use the ...

How to Implement Autocomplete Feature in Angular

CSS <div class="dropdown"> <input type="text" formControlName="itemName" (ngModelChange)="filterItems()" class="dropdown-input" (keyup)="onKeyPress($event)" (blur)="toggleDropdown(0)" (focus)="toggleDropdown(1)" placeholder="Search..." [ngCla ...

Guide to executing a server-side FUNCTION within a specific namespace room exclusively with the help of socket.io, express, and node.js

I've been developing an online multiplayer game using socket.io, express, and node.js. The server is supposed to detect the number of users connected to a specific room within a namespace and start the game if there are more than two players. However, ...

Create a captivating sliding effect on Windows 8 using a combination of CSS and JavaScript

I believe that using css3 alone can achieve this effect, but I'm struggling with understanding properties like 'ease' in css3. This is the progress I have made so far: http://jsfiddle.net/kwgy9/1/ The word 'nike' should slide to ...

Creating Custom Filters in Angular using Functions

Attempting to filter ng-repeat using a function instead of an actual filter has presented some challenges. The code snippet below demonstrates the attempt: <tr ng-repeat="(key, value) in dataObj| filter:dataFilter"> The intention is to define dataF ...

How can the outer function be connected to the resolve method of $routeProvider?

Here is a functional code snippet: $routeProvider.when('/clients', { templateUrl:'/views/clients.html', controller:'clientsController', resolve: { rights: function ( ...

Assign value to twig variable using JavaScript in Symfony version 3.4

Hello everyone, I am currently working on a form that is functioning well. However, I am facing an issue with setting the localization of a place manually using latitude and longitude values. To address this, I decided to create a map with a draggable mark ...

Replicate the functionality of a mouse scrolling event

I have incorporated Jack Moore's Wheelzoom jQuery plugin to zoom and drag an SVG image on my website. However, I also want to include manual zoom in and out buttons for the users. I am considering two options to achieve this - triggering a mouse whe ...

The word "await" is a special reserved keyword used to call functions within an async

Currently utilizing async-await: Whenever the function run invokes findLateastVersion, even though run function is marked as async, an error message pops up stating await is a reserved word. The findLateastVersion method returns a promise and based on va ...