javascriptvue.jsvuejs2vue-router

VueJS: bypass beforeRouteLeave


I have a Vue SPA. Inside a component, I use beforeRouteLeave guard to prevent the user from accidentally leaving the page. Within that component, sometimes I fire an ajax request, which on success it must redirect the page to another location.

The problem is once ajax requests succeeds and $router.push() attempts to perform the redirect, beforeRouteLeave does not allow it.

How can I temporarily bypass beforeRouteLeave and leave the $router perform the redirect?

<script>

methods:{
    someAjaxCall()
    {
        axios.post('...')
        .then(res=>{
            this.$router.push({
                name: 'route.name.here'
            })
        })
    }
},

beforeRouteLeave(to, from, next){
    next(window.confirm('Are you sure? Progress will be discarded.'))
},

</script>

Solution

  • I can use a boolean variable with condition to bypass the guard:

    <script>
    
    data(){
        return {
            avoidRouteLeave: false,
        }
    },
    methods:{
        someAjaxCall()
        {
            axios.post('...')
            .then(res=>{
                this.avoidRouteLeave = true
                this.$router.push({
                    name: 'route.name.here'
                })
            })
        }
    },
    
    beforeRouteLeave(to, from, next){
        if(this.avoidRouteLeave)
            next()
        else
            next(window.confirm('Are you sure? Progress will be discarded.'))
    },
    
    </script>