Understanding the process of accessing data within the beforeRouteLeave component guard in Vue

Having trouble accessing data within beforeRouteLeave as everything appears to be undefined

Check out the code snippet below:

<template>
  ...
</template>

<style lang="scss">
  ...
</style>

<script>

  export default {
    name: 'blog-new',
    data() {
      return {
        isBodyChanged: false,
        isPublished: false,
        isTitleChanged: false,
      }
    },
    created() {
      ...
    },
    beforeRouteLeave: (to, from, next) => {
      console.log(this.isBodyChanged) //<--undefined
      if (this.isBodyChanged) {
        return next(false)
      } else {
        return next()
      }
    }
  }
</script>

Answer №1

To ensure that the this keyword refers to the instance of the component, it is recommended to use an ES5 function instead of an arrow function. Arrow functions utilize lexical scoping.

beforeRouteLeave: function(to, from, next) {
  if (this.isBodyChanged) {
    return next(false)
  } else {
    return next()
  }
}

An alternative shorthand method can also be used for the same functionality:

beforeRouteLeave(to, from, next) {
  if (this.isBodyChanged) {
    return next(false)
  } else {
    return next()
  }
}

Answer №2

Exactly as Dominic mentioned. Make sure to include your function within the methods section.

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

Pass information from the child component to the parent component using Vue.js

I am currently working on a modal component named modal_form.vue, which I am using inside another component called index.vue. My goal is to pass a data variable from modal_form.vue to index.vue. Can anyone provide me with an example of how to achieve this ...

Refreshing the parent page in Oracle Apex upon closing the child window.When the child window

I have created an interactive report with a form where the interactive report is on page 2 as the parent page and the form page is on page 3 as the child page. In the parent page, I have written JavaScript to open a modal window (form page - page 3) using ...

Creating a series of image files from CSS and Javascript animations using Selenium in Python

Looking to convert custom CSS3/Javascript animations into PNG files on the server side and then combine them into a single video file? I found an interesting solution using PhantomJS here. As I am not very familiar with Selenium, adapting it for use with S ...

Enhance the sent server parameters by including extra options in fineuploader

I have successfully implemented file uploads using . Everything works perfectly. I am able to set parameters in the request object to send additional data to the server. However, when I try to add another parameter dynamically using the setParams function ...

Dynamic Component Interactions in VueJS using Mouse Events

Just starting out with Vue and other frameworks, so my approach may not be very "Vue-like". I am attempting to create a versatile button component that can have different behaviors based on a prop, in order to maintain just one button component. The desir ...

Utilizing Supabase queries alongside React's Hot Toast Promise: A Comprehensive Guide

I'm currently working on an admin panel to manage my website. As part of the development, I am using Supabase for the Database and React Hot Toast for notifications. Recently, I attempted to implement Toast Promise using the following code: const add ...

IE Troubles: Timer Function Fails in Asp.Net MVC

I implemented the following code snippet: @Using Ajax.BeginForm("Index", New AjaxOptions() With { _ .UpdateTargetId = "AnswerSN", .HttpMethod = ...

Tips for integrating Excel files with NestJS

I'm in the process of developing a REST API that will utilize a third-party API to retrieve specific status information. The URLs needed for this API are stored in an Excel file, which is a requirement for this use case. My goal is to extract the URLs ...

The primary view seamlessly integrates with the page following the invocation of the partial view

Whenever the button is clicked, a different partial view is returned based on the selected value from the drop-down list. Controller: [HttpPost] public ActionResult Foo(SomeViewModel VM) { var model = VM; if (Request.IsAjaxRequest()) { ...

Linking together or organizing numerous JavaScript function executions in instances where the sequence of actions is crucial

I have implemented a web api method that conducts calculations by using a json object posted to the method. I believe that a jquery post is asynchronous. Assuming this, I want to be able to link multiple calls to the js function invoking this api method in ...

Error: Unable to locate corresponding closing tag for "<%"

I'm struggling to figure out what I might have missed. Everything appears correct, but the nested and somewhat complex code that I am writing seems to be causing an issue with EJS. The variable posts has been passed from node.js to the EJS file. How c ...

I am having trouble with retrieving and showing Json data in a table using axios within a React component

Struggling to access JSON data using hooks to display it in the <p> tag but encountering an error - "TypeError: states.map is not a function". I attempted utilizing Array.from() to convert my JSON to an array, yet it neither displayed anything nor pr ...

Leverage API request within the component

Experimenting with VueJS, I am attempting to execute an api call from a component: var postView = { props: ['post'], template: '<li>{{ post.title }}</li>', url: 'https://jsonplaceholder.typicode.com/posts&a ...

Implementation of Gallows Game

SITUATION Recently, I took on the challenge of creating a "HANGMAN" game using JavaScript and HTML exclusively for client-side machines. The logical part of the implementation is complete, but I am facing a hurdle when it comes to enhancing the aesthetics ...

Using Typescript to create an asynchronous function without explicitly declaring a Promise

When you examine TypeScript's async function, you may notice the redundancy with "async" and "Promise<type>". public async test(): Promise<string> { return "Test"; } Is there a way to configure TypeScript to handle async types ...

Maintain the selected bootstrap tab even after the page is refreshed, even when the content is loaded dynamically

I am currently facing an issue with loading tabs using Angular. Whenever a tab is clicked, the id is saved to localStorage. Now, I want to programmatically click on the same tab using jQuery when the page refreshes. However, since the DOM element for the ...

When trying to install express using Node.js npm, an error message 'CERT_UNTRUSTED' is preventing the installation of express

My goal is to set up express on Raspberry Pi for the purpose of using it in a REST API. However, I keep encountering an issue with SSL certification when trying to install it through npm. Despite attempting various solutions found on different forums, I ha ...

Creating a new version of an existing method found within a component in a Vue store.js file

As I navigate through the learning curve of vue.js, a seemingly simple question has arisen: how can I achieve the following task? Within one of my vue components, I am facing challenges with the implementation of the "loadSuggestedUsers" method. Here is t ...

Seeking particular section of online content in an asynchronous manner

Is there a method for asynchronously requesting a specific portion of a web resource (like the initial 100 bytes) using JavaScript? I believed this could be accomplished through XmlHttpRequest by adjusting its Range header. However, if the server utilizes ...

Variable for Ajax success not set even though the other data was returned

UPDATE: While the main question remains unchanged, I have modified the approach to now return a getButtons() function instead of a global buttons array. I am utilizing an AJAX request to fetch data from the server in order to populate a popup box, which i ...