onBeforeRouteLeave 和 onBeforeRouteUpdate 可以正常在setup中使用
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router';
import { ref } from 'vue'
export default {
setup() {
// 與 beforeRouteLeave 相同,無(wú)法訪問(wèn) `this`
onBeforeRouteLeave((to, from) => {
const answer = window.confirm(
'Do you really want to leave? you have unsaved changes!'
)
// 取消導(dǎo)航并停留在同一頁(yè)面上
if (!answer) return false
})
const userData = ref()
// 與 beforeRouteUpdate 相同,無(wú)法訪問(wèn) `this`
onBeforeRouteUpdate(async (to, from) => {
//僅當(dāng) id 更改時(shí)才獲取用戶,例如僅 query 或 hash 值已更改
if (to.params.id !== from.params.id) {
userData.value = await fetchUser(to.params.id)
}
})
},
}
但beforeRouteEnter無(wú)法在setup語(yǔ)法糖中使用躲雅,只能用其他方法
方法一
<script lang="ts">
export default {
beforeRouteEnter(to: any, from: any) {
console.log("salesOrder beforeRouteEnter",to ,from)
},
beforeRouteLeave(to: any, from: any) {
console.log("salesOrder beforeRouteLeave",to ,from)
},
}
</script>
<script setup lang="ts" name="xxx">
// 語(yǔ)法糖代碼
</script>
該方法的問(wèn)題是不同script標(biāo)簽內(nèi)的數(shù)據(jù)是不相通的
方法二
export default {
beforeRouteEnter(to, from, next) {
// balabala
},
setup() {
// balabala
}
}