简述uniApp项目页面之间传值 ?

在 uni-app 中,页面之间的传值主要依赖于路由跳转时的参数传递、全局状态管理以及本地存储等机制。以下是几种常见的页面传值方法:

1. 路由传参

当使用路由跳转(如uni.navigateTo)时,可以通过URL传递参数。

发送方

// 使用 navigateTo 跳转并传递参数
uni.navigateTo({
  url: '/pages/targetPage/targetPage?param1=value1&param2=value2'
});

接收方

在目标页面的 onLoad 方法中,可以通过 options 参数接收到传递的参数。

export default {
  onLoad(options) {
    console.log(options.param1); // value1
    console.log(options.param2); // value2
  }
}

2. 全局状态管理(Vuex)

对于复杂的应用,可以使用 Vuex 来管理需要跨页面共享的状态。通过在全局状态树中存储数据,各个页面通过修改状态或读取状态来实现数据共享和传递。

定义全局状态

// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    sharedData: 'initial value'
  },
  mutations: {
    updateSharedData(state, newValue) {
      state.sharedData = newValue;
    }
  }
});

export default store;

修改和读取状态

// 修改状态
this.store.commit('updateSharedData', 'new value');

// 读取状态
console.log(this.store.state.sharedData);

3. 本地存储(LocalStorage/uni.setStorage)

对于需要持久化存储的数据或较大数据量的传递,可以使用本地存储的方式。这包括 Web 的 LocalStorage 或 uni-app 提供的 uni.setStorage API。

设置数据

uni.setStorage({
  key: 'someKey',
  data: 'some value',
  success: function () {
    console.log('数据保存成功');
  }
});

获取数据

uni.getStorage({
  key: 'someKey',
  success: function (res) {
    console.log(res.data); // 'some value'
  }
});

4. 事件总线(Event Bus)

对于非父子组件间的复杂通信,可以使用事件总线(Event Bus)来传递数据。通过创建一个全局的 Vue 实例作为中央事件总线,可以在任何组件中触发事件和监听事件。

创建事件总线

// event-bus.js
import Vue from 'vue';
export const EventBus = new Vue();

发送数据

import { EventBus } from './event-bus.js';
EventBus.$emit('eventName', data);

接收数据

import { EventBus } from './event-bus.js';
EventBus.$on('eventName', data => {
  console.log(data);
});

通过上述方法,可以根据不同的场景和需求,在 uni-app 项目的页面之间进行有效的数据传递和共享。