[Vuejs]-Vue router back button prevent navigation to previous domain

1๐Ÿ‘

I think you can try to measure history.length in different cases. And try to find a pattern of the cases where the user is arrived at the page from different domain and from the vue-router navigation.

When I was dealing with such navigation, I used to create composable function to control back navigation from different pages.

Consider this example:

const backNavigationFnRef = ref(defaultBackNavigationFn)

export const useNavigation = () => {
  const router = useRouter()
  const defaultBackNavigationFn = () => {
      router.go(-1)
  }
  const setBackNavigationFn = (fn) => {
    backNavigationFnRef.value = fn
  }
  const resetNavigationFn = () => {
    setBackNavigationFn(defaultBackNavigationFn)
  }

  return {
   backNavigationFnRef,
   resetNavigationFn,
   setBackNavigationFn
  }
}

Now in most cases, back button will just use defaultBackNavigationFn, and if you want to handle specific pages to always navigate back to a certain page, then use:

_id.vue

<script setup>
 import {useNavigation} from '...'
 const {setBackNavigationFn} = useNavigation()

 setBackNavigationFn(() => {
   // here you can write custom back navigation logic
 })
</script>

in Layout.vue

...
const {backNavigationFnRef} = useNavigation()
...
<Header @onBackBtnClick="() => backNavigationFnRef.value()" />
๐Ÿ‘คRassulzhan

Leave a comment