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

What is the best way to modify just a portion of the state in React?

Consider the following State object: const initialState = { data: { user: '', token: '', } } In the Reducer function: case 'DO_SOMETHING': return {...state, data: action.payload } If I make a shallow copy of th ...

Element obscured by dropdown content now clearly visible thanks to dropdown adjustment

Something strange is happening here - the Add question div shouldn't be visible. It's somehow appearing behind the dropdown content. I've attempted to adjust the z-index of the Add Question div, setting it to a lower number than the dropdown ...

bindings and validation of input values in angularjs

In my scenario, I am dealing with a dynamic regExp and unique masks for each input. For instance, the regExp is defined as [0-9]{9,9} and the corresponding mask is XXX-XX-XX-XX. However, when it comes to Angular's pattern validation, this setup is con ...

The FB API does not request permission to manage_pages

When logging in as the user who created the app, they are prompted to grant both manage_pages and publish_stream permissions. However, when logging in as a different user, only the publish_stream permission is requested and granted; manage_pages access is ...

A guide on breaking down a URL string containing parameters into an array with the help of JavaScript

I need help splitting a long string into an array with specific index structure like this: fname=bill&mname=&lname=jones&addr1=This%20House&... I am looking to have the array set up as shown below: myarray[0][0] = fname myarray[0][1] = b ...

Differences between MobX local state and global state

I am currently working on a React project using mobx to manage the application state. For dump components that interact with external data sources (such as ajax calls, filtering or mapping arrays), I simply manipulate the data in those components. Howeve ...

What are the implications of declaring a controller as a variable within itself or utilizing $scope?

As I dive into learning and utilizing AngularJS, certain concepts still remain unclear to me. Here is my query: within my application, there is a controller that utilizes $http to fetch data from the backend upon initialization. Following a comprehensive ...

Tips for passing parent component state data to a child component using a variable

In my index.js file, I have a parent component with a state variable x:[] that contains data [{…}, {…}, {…}]. Now, in my child component (child.jsx), I need to save this parent component data [{…}, {…}, {…}] in a variable within the child compo ...

Navigating through the year selection with your keyboard

By default, a dropdown menu containing years allows for keyboard navigation. For example, if you type in 1992 while the dropdown is selected, it will automatically move to that specific year option. I am curious to know if there is a way to activate a two ...

Angular Material has support for displaying nested optgroups within select components

Upon reviewing a question on Stack Overflow, I learned that nested optgroups are not supported in the HTML5 spec. While it is possible to manually style them, I am curious if Angular Material offers a solution. Angular Material internally swaps many eleme ...

express-locale: locales property not functioning as intended

I've been experimenting with using express-locale (v1.0.5) as middleware in my express app to identify the locale based on the browser request. My goal is to compare the identified locale with a list of 'allowed' locales and use a default i ...

An issue with Nuxt.js causing body parameters to not be passed successfully while using this.$http.post

I've encountered an issue where using the @nuxt/http this.$http.post and this.$http.patch methods is causing problems with parsing body parameters during posting. Strangely, it used to work perfectly fine before, leaving me unsure of where to even beg ...

The message sent back by Django Rest Framework is: "a legitimate integer must be provided"

I have integrated a react form within my Django application, supported by the rest framework in the backend. When I submit the form without entering any value in the integer field, I encounter the following error message from the rest API: "a valid integer ...

A simple method for bulk editing in Angular UI Grid

Is there a way to enable mass editing in Angular UI Grid by allowing all rows to show editable input fields at once, rather than just one at a time? I have searched online for a solution without success and am now turning to this forum for help. If anyone ...

Three.js - Model is unable to cast shadows

Greetings! I am currently diving into the world of three.js and utilizing react-three-fiber to integrate it with React. However, I've encountered a challenge regarding shadow casting between models. Despite setting obj.castShadow = true and obj.receiv ...

An AJAX function nested within another AJAX function

Is there a way for me to return the second ajax call as the result of the ajax function? I could use some assistance with this. function ajax(url: string, method:string, data:any = null) { var _this = this; return this.csrfWithoutDone().done(funct ...

ngResource transformResponse guide on dealing with both successful and erroneous responses

When my API, built using expressJS, returns JSON data as a regular response, everything functions smoothly. However, when an error occurs, it returns an error code along with plain text by simply invoking res.sendStatus(401). This poses a challenge on my ...

Is it possible to utilize Javascript instead of PHP Curl to present JSON API data?

After successfully displaying JSON API data from openweathermap.org on my HTML webpage using PHP Curl, I am now seeking help to achieve the same output using Javascript. My PHP script retrieves JSON data from the source, and here is a snippet of that PHP c ...

A feature to reveal additional content when it extends beyond a single line

<div class="questionnaire-description col-xs-12" id="questionnaire_description_wrapper"> <text-truncate> <span ng-class="questionnaire_description.show_more ? 'full-description' : 'ph-ellips ...

The jQuery load() callback triggering a POST request unexpectedly instead of a GET request

Utilizing jQuery's load() method, I am attempting to insert a page fragment into a new page. It appears that this can only be achieved with load(), as get() does not support page fragments. Upon completion of the load, it is necessary for me to invok ...