interceptor.uvue 1.7 KB
Newer Older
Q
qiang 已提交
1
<template>
2 3 4 5 6 7
  <view>
    <button @click="addInterceptor">添加路由拦截器</button>
    <button @click="removeInterceptor">移除路由拦截器</button>
    <text>点击下方按钮{{msg}}</text>
    <button @click="navigateTo">跳转到测试页面</button>
  </view>
Q
qiang 已提交
8 9 10
</template>

<script>
11 12 13 14 15 16 17 18 19 20 21 22 23 24
  const interceptor = {
    invoke: function (options : NavigateToOptions) {
      console.log('interceptor.invoke:', options)
      const url = './page2'
      uni.showToast({
        title: `重定向到页面:${url}`
      })
      options.url = url
    },
    success: function (res : NavigateBackSuccess) {
      console.log('interceptor.success:', res)
    },
    fail: function (err : NavigateToFail) {
      console.log('interceptor.fail:', err)
Q
qiang 已提交
25
    }
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
  } as Interceptor
  export default {
    data() {
      return {
        msg: "会跳转到测试页面1"
      }
    },
    beforeUnmount() {
      // 移除 navigateTo 所有拦截器
      uni.removeInterceptor('navigateTo')
    },
    methods: {
      addInterceptor() {
        uni.addInterceptor('navigateTo', interceptor)
        uni.showToast({
          title: '页面跳转已拦截'
        })
        this.msg = ",路由被劫持到测试页面2"
      },
      removeInterceptor() {
        uni.removeInterceptor('navigateTo', interceptor)
        uni.showToast({
          title: '拦截器已移除'
        })
        this.msg = "会跳转到测试页面1"
      },
      navigateTo() {
        uni.navigateTo({
          url: './page1',
          success(res) {
            console.log('res:', res)
          },
          fail(err) {
            console.error('err:', err)
          }
        })
      }
    }
  }
Q
qiang 已提交
65 66 67 68
</script>

<style>

69
</style>