interceptor.uvue 1.5 KB
Newer Older
Q
qiang 已提交
1
<template>
2 3 4 5 6
  <view>
    <button @click="addInterceptor">添加拦截器</button>
    <button @click="removeInterceptor">移除拦截器</button>
    <button @click="navigateTo">跳转到测试页面</button>
  </view>
Q
qiang 已提交
7 8 9
</template>

<script>
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
  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)
    }
  } as Interceptor
  export default {
    data() {
      return {
Q
qiang 已提交
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
      }
    },
    beforeUnmount() {
      // 移除 navigateTo 所有拦截器
      uni.removeInterceptor('navigateTo')
    },
    methods: {
      addInterceptor() {
        uni.addInterceptor('navigateTo', interceptor)
        uni.showToast({
          title: '拦截器已添加'
        })
      },
      removeInterceptor() {
        uni.removeInterceptor('navigateTo', interceptor)
        uni.showToast({
          title: '拦截器已移除'
        })
      },
      navigateTo() {
        uni.navigateTo({
          url: './page1',
          success(res) {
            console.log('res:', res)
          },
          fail(err) {
            console.error('err:', err)
          }
        })
      }
Q
qiang 已提交
60
    }
61
  }
Q
qiang 已提交
62 63 64 65 66
</script>

<style>

</style>