返回

灵活转换多页面!uniapp 开发钉钉小程序使用 web-view 的技巧

前端

问题

在uniapp中开发钉钉小程序时,经常会遇到使用web-view加载h5页面,却无法返回钉钉小程序上一个页面的问题。这是一个常见的问题,网上也有许多讨论和解决方案,但很多都难以理解或操作复杂。

解决方案

要解决此问题,我们需要在uniapp项目中添加以下代码:

// 在manifest.json文件中添加以下代码
{
  "permission": {
    "scoped": true
  },
  "app-plus": {
    "webview": {
      "directory": "public"
    }
  }
}
// 在app.vue文件中添加以下代码
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    webviewCanGoBack: false
  },
  mutations: {
    setWebviewCanGoBack (state, canGoBack) {
      state.webviewCanGoBack = canGoBack
    }
  }
})
// 在pages.json文件中添加以下代码
{
  "tabBar": {
    "list": [
      {
        "pagePath": "pages/index/index",
        "text": "首页",
        "iconPath": "static/images/tabbar/home.png",
        "selectedIconPath": "static/images/tabbar/home_active.png"
      },
      {
        "pagePath": "pages/web-view/web-view",
        "text": "web-view",
        "iconPath": "static/images/tabbar/app.png",
        "selectedIconPath": "static/images/tabbar/app_active.png"
      }
    ]
  }
}
// 在pages/web-view/web-view.vue文件中添加以下代码
<template>
  <view>
    <web-view :src="url" @did-navigate-before="onDidNavigateBefore" @did-navigate-after="onDidNavigateAfter"></web-view>
  </view>
</template>

<script>
import { mapState } from 'vuex'

export default {
  data () {
    return {
      url: 'http://www.baidu.com'
    }
  },
  computed: {
    ...mapState(['webviewCanGoBack'])
  },
  methods: {
    onDidNavigateBefore (e) {
      if (e.detail.url === 'http://www.baidu.com') {
        this.$store.commit('setWebviewCanGoBack', false)
      } else {
        this.$store.commit('setWebviewCanGoBack', true)
      }
    },
    onDidNavigateAfter (e) {
      if (e.detail.url === 'http://www.baidu.com') {
        this.$store.commit('setWebviewCanGoBack', false)
      } else {
        this.$store.commit('setWebviewCanGoBack', true)
      }
    }
  }
}
</script>

总结

通过以上步骤,我们就可以解决uniapp中使用web-view加载h5页面时无法返回钉钉小程序上一个页面的问题。希望本文对您有所帮助。

附加技巧

以下是一些在uniapp中开发钉钉小程序时可能用到的技巧:

  • 使用 scoped 属性来限制样式的作用范围,可以避免样式污染。
  • 使用 app-plus 属性来配置钉钉小程序的原生功能,如导航栏、状态栏等。
  • 使用 webview 属性来配置 web-view,如 directory、preload 等。
  • 使用 manifest.json 文件来配置钉钉小程序的基本信息,如名称、图标、权限等。
  • 使用 pages.json 文件来配置钉钉小程序的页面路由。
  • 使用 store 来管理钉钉小程序的数据。
  • 使用 router 来管理钉钉小程序的页面跳转。