[Vue.js] beforeRouteLeave ํ™œ์šฉ

beforeRouteLeave

์‚ฌ์šฉ์ž์—๊ฒŒ ์ž…๋ ฅ์„ ์š”๊ตฌํ•˜๋Š” ํŽ˜์ด์ง€์—์„œ, ์‚ฌ์šฉ์ž์˜ ์‹ค์ˆ˜๋กœ ์ธํ•ด(backspace, ์ž˜ ๋ชป ๋ˆ„๋ฆ„)๋“ฑ ์ž‘์„ฑ ์ค‘์ธ ํŽ˜์ด์ง€๋ฅผ ๋„˜์–ด๊ฐˆ ๋•Œ๊ฐ€ ์žˆ๋‹ค.
์ด๋Ÿฐ ์ƒํ™ฉ์„ ๋ง‰๊ธฐ ์œ„ํ•ด beforeRouteLeave ์ด์šฉํ•˜์—ฌ ์‚ฌ์šฉ์ž์—๊ฒŒ ํŽ˜์ด์ง€๋ฅผ ๋„˜์–ด๊ฐ€๊ธฐ ์ „ ํ™•์ธ์„ ์š”์ฒญ๋ฐ›์„ ์ˆ˜ ์žˆ๋‹ค.

์‚ฌ์šฉ๋ฒ•

    beforeRouteLeave(to, from, next) {
      // to => ํ˜„์žฌ ๋Œ€์ƒ route ๊ฐ์ฒด
      // from => ์ด ๋ผ์šฐํŠธ๋กœ ์˜ค๊ธฐ์ „ ๋ผ์šฐํŠธ
      // next => ์ด๋™ํ•  ๋ผ์šฐํŠธ
    }

๋ฐ˜๋“œ์‹œ next()๋ฅผ ์„ ์–ธํ•ด์•ผ ๋˜๋ฉฐ, next()๋ฅผ ์„ ์–ธํ•˜์ง€ ์•Š์„ ์‹œ ์ด๋™์„ ๋ง‰์–ด๋ฒ„๋ฆฐ๋‹ค.(guard) ์›ํ•˜๋Š” ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋ฉด next()๋กœ ์ด๋™์„ ํ•˜๊ฒŒ ํ•ด์ฃผ๊ณ , ๊ฐ€๋“œ๋ฅผ ์›ํ•˜๋ฉด next(false)๋ฅผ ์‚ฌ์šฉํ•˜์ž.

์œ„์น˜

<template>
 ...
</template>
<script>
  export default {
        beforeRouteLeave(to, from, next) {
        if (this.certification) next()
        else this.nextConfirm(next)
    },
  ...
  }
  ...
</script>

์ปดํฌ๋„ŒํŠธ ๋‚ด๋ถ€ ๊ฐ€๋“œ์ด๊ธฐ ๋•Œ๋ฌธ์— vue ์ปดํฌ๋„ŒํŠธ์—์„œ script ์•ˆ์˜ export default์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

์˜ˆ์ œ

    beforeRouteLeave(to, from, next) {
        if (this.certification) next() // certification == true๋ผ๋ฉด ํŽ˜์ด์ง€ ์ด๋™ ํ—ˆ์šฉ
        else this.nextConfirm(next) // ๋งŒ๋“ค์–ด๋‘” async method ์‚ฌ์šฉ
    }

ํŽ˜์ด์ง€ ์ž‘์„ฑ, ์ˆ˜์ • ๋“ฑ ์˜๋„ํ•œ ๋ฒ„ํŠผ์„ ํด๋ฆญ ์‹œ certification์„ ํ™•์ธํ•˜์—ฌ ๋ฐ”๋กœ ๋„˜์–ด๊ฐ€๊ฒŒ ํ•ด์คฌ๊ณ ,
๊ทธ ์™ธ์˜ ๊ฒฝ๋กœ๋กœ ํŽ˜์ด์ง€๋ฅผ ๋ฒ—์–ด๋‚˜๋ ค๊ณ  ํ•  ๋•, next ํ•จ์ˆ˜๋ฅผ ์ธ์ž๋กœ ๋„ฃ์€ async ๋ฉ”์†Œ๋“œ๋ฅผ ํ†ตํ•ด ์‚ฌ์šฉ์ž๊ฐ€ ์„ ํƒํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์คฌ๋‹ค.