Back

How to get the path of previous url in NuxtJs

I was working on a Vue component in NuxtJs and wanted to get the path of the previous page. There's a way to use the beforeRouteEnter navigation guard like below.

data() {
  return {
    prevPath: null,
  }
},
beforeRouteEnter(to, from, next) {
  next(vm => vm.prevPath = from);
}

Here we define the data variable in component and set that before the navigation enters the route as in above code. However, this approach was not working in my component. I found another way to get the previous path 

mounted() {
    const { fullPath: prevPath } = { ...this.$nuxt.context.from };
    console.log(prevPath)
}

If we want to use the previous path just to redirect back on a button click then we can use the below method as well

methods: {
    goBack() {
        this.$router.go(-1);
    }
}

Below is the code that i got from ChatGPT when i asked it. You can give it a go.

export default {
  name: 'MyComponent',
  data() {
    return {
      previousRoute: ''
    }
  },
  created() {
    this.previousRoute = this.$route.fullPath;
  },
  beforeRouteUpdate(to, from, next) {
    this.previousRoute = from.fullPath;
    next();
  }
}
nuxtjsvuejsrouterprevious urlprevious pathjavascriptvue component

Latest Post

Information retrieval – Searching of text using Elasticsearch

Information retrieval is the process of obtaining relevant information resources from the collection of resources relevant to information need.

Learn more
© 2023 www.lamadly.com