updated: 2020/10/16
環境:
vue@2.6.12
vuex@3.5.1
vue-router@3.4.6
Goal:
あるユーザーのポストにダイレクトにアクセス時、
modal を閉じると当該ユーザーのプロフィールページに移行。
また、タイムラインからあるユーザーのポストにアクセス時、
modal を閉じるとタイムラインにバック。
solution)
beforeRouteEnter()でroutingの状態をstateに保存し、modalを閉じたときの挙動を保存した状態に応じて制御。
beforeRouteEnter(to, from, next) {
next(vm => {
vm.router_setStatus({from from, to: to}) // router_setStatus はstateに保存するvuex action とする。ここでは割愛。
})
}
closeModal() {
if(this.$store.state.router.from) {
this.$router.go(-1) // fromがある→direct access ではないので前のページに戻る
} else {
this.$router.push('USER_PROFILE_PAGE') // ユーザーのプロフィールページへ移行
**need fix)
modal の背景をダイレクトアクセスとそれ以外できりかえることは可能だが、beforeRouteEnterが都度コールされないので初めに定義したcomponentでしか表示されない。妥協して背景は表示しないこととした。
下記のようにmodal以外にnamed router-view を指定するとinitialアクセス時は意図したようにconditionalが機能するが、以降のアクセスはnamed router-viewが再定義されない。
<router-view></router-view>
<router-view name="modal"></router-view>
<router-view name="profile"></router-view>
beforeRouteEnter(to, from, next) {
↑↑
<router-view>で使用するcomponentを定義している。
ref:
}
}