onBeforeRouteLeave 和 onBeforeRouteUpdate 可以正常在setup中使用
import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router';
import { ref } from 'vue'
export default {
setup() {
// 与 beforeRouteLeave 相同,无法访问 `this`
onBeforeRouteLeave((to, from) => {
const answer = window.confirm(
'Do you really want to leave? you have unsaved changes!'
)
// 取消导航并停留在同一页面上
if (!answer) return false
})
const userData = ref()
// 与 beforeRouteUpdate 相同,无法访问 `this`
onBeforeRouteUpdate(async (to, from) => {
//仅当 id 更改时才获取用户,例如仅 query 或 hash 值已更改
if (to.params.id !== from.params.id) {
userData.value = await fetchUser(to.params.id)
}
})
},
}
但beforeRouteEnter无法在setup语法糖中使用,只能用其他方法
方法一
<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">
// 语法糖代码
</script>
该方法的问题是不同script标签内的数据是不相通的
方法二
export default {
beforeRouteEnter(to, from, next) {
// balabala
},
setup() {
// balabala
}
}
网友评论