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

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

<style>

Q
qiang 已提交
75
</style>