在實際工作中有很多場景需要在第二個頁面中將用戶操作之后的將數據回傳到上一頁面。接下來將我的方案分享給小伙伴。 本次示例采用 uni-app 框架和 weui 樣式庫 實現思路 創建一個 Emitter,用於事件處理 創建一個 ...
在實際工作中有很多場景需要在第二個頁面中將用戶操作之后的將數據回傳到上一頁面。接下來將我的方案分享給小伙伴。
本次示例采用 uni-app 框架和 weui 樣式庫
實現思路
- 創建一個
Emitter ,用於事件處理
- 創建一個全局的
Storage
- 在第一個頁面創建一個
emitter 對象,並添加事件監聽,將 emitter 存儲到 Storage 中
- 在第二個頁面從
Storage 中取出 emitter 對象, 並觸發事件,將數據傳遞到第一個頁面中做處理
創建 Emitter
function isFunc(fn) { return typeof fn === 'function'; } export default class Emitter { constructor() { this._store = {}; }
創建 Storage
export class Storage { constructor() { this._store = {}; } add(key, val) { this._store[key] = val; } get(key) { return this._store[key]; } remove(key) { delete this._store[key]; } clear() { this._store = {}; } } export default new Storage(); 復制代碼
第一個頁面中的處理
<template> <div class="page"> <div class="weui-cells__title">選擇城市</div> <div class="weui-cells weui-cells_after-title"> <navigator :url="`../select/select?id=${cityId}`" class="weui-cell weui-cell_access" hover-class="weui-cell_active"> <div class="weui-cell__hd weui-label">所在城市</div> <div class="weui-cell__bd" :style="{color: cityName || '#999'}">{{ cityName || '請選擇' }}</div> <div class="weui-cell__ft weui-cell__ft_in-access"></div> </navigator> </div> </div> </template> <script> import Emitter from '../../utils/emitter'; import storage from '../../utils/storage'; export default { data() { return { cityId: '', cityName: '', } }, onLoad() { const emitter = new Emitter();
第二個頁面中的處理
<template>
<div class="page"> <div class="weui-cells__title">城市列表</div> <div class="weui-cells weui-cells_after-title"> <radio-group @change="handleChange"> <label class="weui-cell weui-check__label" v-for="item in list" :key="item.id"> <radio class="weui-check" :value="item.id" :checked="`${item.id}` === selectedId" /> <div class="weui-cell__bd">{{ item.text }}</div> <div v-if="`${item.id}` === selectedId" class="weui-cell__ft weui-cell__ft_in-radio"> <icon class="weui-icon-radio" type="success_no_circle" size="16" /> </div> </label> </radio-group> </div> </div> </template> <script> import storage from '../../utils/storage'; export default { data() { return { list: [ { id: 0, text: '北京' }, { id: 1, text: '上海' }, { id: 2, text: '廣州' }, { id: 3, text: '深圳' }, { id: 4, text: '杭州' }, ], selectedId: '' } }, onLoad({ id }) { this.selectedId = id; // 取出 emitter this.emitter = storage.get('indexEmitter'); }, methods: { handleChange(e) { this.selectedId = e.detail.value; const item = this.list.find(({ id }) => `${id}` === e.detail.value); // 觸發事件並傳遞數據 this.emitter.emit('onSelect', { ...item }); } } } </script> 復制代碼
效果展示

傳送門
github
總結
之所以將Storage 定義成全局的,是為了保證第一個頁面放到Storage 中和第二個頁面從 Storage 中取出的emitter 是同一個實例,如此第一個頁面才能正確監聽到第二個頁面觸發的事件。也可以使用 vuex,將 emitter 放到 state 中。
|
轉自:http://www.wxapp-union.com/article-5740-1.html