Uni-App 页面间传值方法详解

在 Uni-App 开发中,页面之间传递数据是常见需求。本文将介绍两种常用的传值方式,并提供代码示例。

1. 使用页面间 props 传值

  • 在页面 A 中,将要传递的参数以 props 的形式传递给页面 B。
  • 在页面 B 中,可以通过 this.props 来获取传递的参数。

示例代码:

页面 A:

<template>
  <view>
    <navigator url='../B/B' :props='{name: '张三', age: 18}'>
      跳转页面 B
    </navigator>
  </view>
</template>

页面 B:

<template>
  <view>
    <text>姓名: {{props.name}}</text>
    <text>年龄: {{props.age}}</text>
  </view>
</template>

2. 使用 URL 传值

  • 在页面 A 中,通过 uni.navigateTo({url: '../B/B?name=xxx'}) 将参数传递给页面 B。
  • 在页面 B 中,可以通过 uni.getStorageSync() 来获取传递的参数。

示例代码:

页面 A:

<template>
  <view>
    <button @tap='navigateToB'>跳转页面 B</button>
  </view>
</template>

<script>
export default {
  methods: {
    navigateToB() {
      uni.navigateTo({
        url: '../B/B?name=李四&age=20'
      })
    }
  }
}
</script>

页面 B:

<template>
  <view>
    <text>姓名: {{name}}</text>
    <text>年龄: {{age}}</text>
  </view>
</template>

<script>
export default {
  data() {
    return {
      name: '',
      age: '',
    }
  },
  onLoad() {
    const query = uni.getStorageSync('query');
    this.name = query.name;
    this.age = query.age;
  }
}
</script>

注意:

  • 使用 URL 传值时,参数会显示在 URL 中,安全性较低。
  • 建议在传递敏感信息时,使用更安全的加密方式。
Uni-App 页面间传值方法详解

原文地址: http://www.cveoy.top/t/topic/lhxT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录