interceptor.uvue 2.2 KB
Newer Older
Q
qiang 已提交
1
<template>
2
  <view style="flex: 1">
3 4
    <button @click="addInterceptor">添加路由拦截器</button>
    <button @click="removeInterceptor">移除路由拦截器</button>
5 6 7 8 9
    <text>点击下方按钮{{ msg }}</text>
    <button @click="navigateTo">navigatorTo API跳转到测试页面</button>
    <navigator url="./page1"><button class="navigatorButton">
        navigator组件跳转到测试页面
      </button></navigator>
10
  </view>
Q
qiang 已提交
11 12 13
</template>

<script>
14 15
  const interceptor = {
    invoke: function (options : NavigateToOptions) {
Q
qiang 已提交
16
      console.log('拦截 navigateTo 接口传入参数为:', options)
17 18 19 20 21 22
      const url = './page2'
      uni.showToast({
        title: `重定向到页面:${url}`
      })
      options.url = url
    },
23
    success: function (res : NavigateToSuccess) {
Q
qiang 已提交
24
      console.log('拦截 navigateTo 接口 success 返回参数为:', res)
25 26
    },
    fail: function (err : NavigateToFail) {
Q
qiang 已提交
27 28 29 30
      console.log('拦截 navigateTo 接口 fail 返回参数为:', err)
    },
    complete: function (res : NavigateToComplete) {
      console.log('拦截 navigateTo 接口 complete 返回参数为:', res)
Q
qiang 已提交
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 65
  } 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 已提交
66 67 68
          },
          complete(res) {
            console.log('res:', res)
69 70 71 72 73
          }
        })
      }
    }
  }
74
</script>