首页 > 编程语言 >03_微信小程序页面之间的数据通信

03_微信小程序页面之间的数据通信

时间:2024-04-24 13:12:12浏览次数:24  
标签:03 数据通信 微信 js miniprogram 组件 import data computed

 

1. 父传值子,数据绑定: properties

Component({
  properties: {
    propA: {
      type: String, // 传递的数据类型
      value: '' // 默认值
    },
    propB: Number // 简化的定义方式
  }
})
<!-- 引用组件的页面模板 -->
<view>
  <costom propA="{{ name }}" propB="{{ age }}" />
</view>

 

2. 获取子组件实例:this.selectComponent()

<!-- 父组件 -->
<costom bind:myevent="getData" class="custom" /><!--子组件-->
<button bindtap="getChildComponent"></button>
// 父组件
Page({
  data: {},
  getChildComponent: function () {
    const child = this.selectComponent('.custom')
    console.log(child)
  }
})

 

3. 子传父,事件绑定:this.triggerEvent()

自定义组件:

<!-- 在自定义组件中 -->
<button type="primary" plain bindtap="sendData">传递数据</button>
Component({
  // 组件的初始数据
  data: {
    num: 666
  },
  // 组件的方法列表
  methods: {
    // 将数据传递给父组件
    sendData () {
      // 如果需要将数据传递给父组件
      // 需要使用 triggerEvent 发射自定义事件
      // 第二个参数,是携带的参数
      this.triggerEvent('myevent', this.data.num)
    }
  }
})

父组件中:

<view>{{ num }}</view>
<!-- 需要在自定义组件标签上通过 bind 方法绑定自定义事件,同时绑定事件处理函数 -->
<custom05 bind:myevent="getData" />
Page({
  data: {
    num: ''
  },
  getData (event) {
    // 可以通过事件对象.detail 获取子组件传递给父组件的数据
    // console.log(event)
    this.setData({
      num: event.detail
    })
  }
})

 

4. 获取应用实例:getApp()

app.js

App({
  // 全局共享的数据
  globalData: {
    token: ''
  },
  // 全局共享的方法
  setToken (token) {
    // 如果想获取 token,可以使用 this 的方式进行获取
    this.globalData.token = token
    // 在 App() 方法中如果想获取 App() 实例,可以通过 this 的方式进行获取
    // 不能通过 getApp() 方法获取
  }

})

index.js

// getApp() 方法用来获取全局唯一的 App() 实例
const appInstance = getApp()
Page({
  login () {
    // 不要通过 app 实例调用钩子函数
    console.log(appInstance)
    appInstance.setToken('fghioiuytfghjkoiuytghjoiug')

  }

})

 

5. 页面间通信:EventChannel

a.js

Page({
  // 点击按钮触发的事件处理函数
  handler () {
    wx.navigateTo({
      url: '/pages/list/list',
      events: {
        // key:被打开页面通过 eventChannel 发射的事件
        // value:回调函数
        // 为事件添加一个监听器,获取到被打开页面传递给当前页面的数据
        currentevent: (res) => {
          console.log(res)
        }
      },
      success (res) {
        // console.log(res)
        // 通过 success 回调函数的形参,可以获取 eventChannel 对象
        // eventChannel 对象给提供了 emit 方法,可以发射事件,同时携带参数
        res.eventChannel.emit('myevent', { name: 'tom' })
      }
    })
  }
})

b.js

Page({
  onl oad () {
    // 通过 this.getOpenerEventChannel() 可以获取 EventChannel 对象
    const EventChannel = this.getOpenerEventChannel()
    // 通过 EventChannel 提供的 on 方法监听页面发射的自定义事件
    EventChannel.on('myevent', (res) => {
      console.log(res)
    })
    // 通过 EventChannel 提供的 emit 方法也可以向上一级页面传递数据
    // 需要使用 emit 定义自定义事件,携带需要传递的数据
    EventChannel.emit('currentevent', { age: 10 })
  }
})

 

6. 事件总线:pubsub-js

安装命令:npm install pubsub-js 

使用publish发布消息

import { publish } from 'pubsub-js'

publish('dataId',data)

使用subscribe函数订阅消息

import { subscribe } from 'pubsub-js'

subscribe('dataId',(msg,val)=>{
console.log('dataId值',val)
console.log(msg)
})

 

7.mobx-miniprogram和mobx-miniprogram-bindings工具库

   mobx-miniprogram 的作用:创建 Store 对象,用于存储应用的数据
   mobx-miniprogram-bindings 的作用:将状态和组件、页面进行绑定关联,从而在组件和页面中操作数据

   安装:npm install mobx-miniprogram mobx-miniprogram-bindings

numstore.js

// observable:用于创建一个被监测的对象,对象的属性就是应用的状态(state),这些状态会被转换成响应式数据。
// action:用于显式的声明创建更新 state 状态的方法
import { observable, action } from 'mobx-miniprogram'
// 使用 observable 创建一个被监测的对象
export const numStore = observable({
  // 创建应用状态
  numA: 1,
  numB: 2,
  // 使用 action 更新 numA 以及 numB
  update: action(function () {
    this.numA+=1
    this.numB+=1
  }),
  // 计算属性,使用 get 修饰符,
  get sum() {
    return this.numA + this.numB;
  }
})

组件.js

导入的数据fields会同步到组件的 data 中

导入的方法actions会同步到组件的 methods 中

import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { numStore } from '../../stores/numstore'

ComponentWithStore({
  data: {
    someData: '...'
  },
  storeBindings: {
    store: numStore,
    fields: ['numA', 'numB', 'sum'],
    actions: ['update']
  }
})

页面.js和组件.js写法一样。

 

绑定多个 store 以及命名空间:

storeBindings内可以绑定多个store对象

// behaviors.js
import { BehaviorWithStore } from 'mobx-miniprogram-bindings'
import { numStore } from '../../stores/numstore'
export const indexBehavior = BehaviorWithStore({
  storeBindings: [
    {
      namespace: 'numStore',
      store: numStore,
      fields: ['numA', 'numB', 'sum'],
      actions: ['update'],
    }
  ]
})

页面.js

import { cartBehavior } from './behaviors'

Page({
behaviors:[cartBehavior ]
})

 

<view>{{ numStore.numA }} + {{ numStore.numB }} = {{numStore.sum}}</view>

 

 

storeBindings中fields和actions采用对象写法:

fields: {
      // 使用函数方式获取 Store 中的数据
      a: () => store.numA,
      b: () => store.numB,

      // 使用映射形式获取 Store 中的数据,值为数据在 store 中对应的名字
      total: 'sub'
    },

    // 使用映射形式获取 Store 中的 action 名字
    actions: {
      // key 自定义,为当前组件中调用的方法
      // 值为 store 中对应的 action 名字
      buttonTap: 'update'
    }

 

 

08.miniprogram-computed工具库

安装命令:npm install miniprogram-computed

该工具库提供了两个功能:

1. 计算属性 computed
2. 监听器 watch

 

// 引入 miniprogram-computed
import { ComponentWithComputed } from 'miniprogram-computed'

ComponentWithComputed({
    
  data: {
    a: 1,
    b: 1
  },
    
  computed: {
    total(data) {
      // 注意: 
      // computed 函数中不能访问 this ,只有 data 对象可供访问
      // 这个函数的返回值会被设置到 this.data.sum 字段中
      return data.a + data.b
    }
  }
  
  watch: {
    // 同时对 a 和 b 进行监听
    'a, b': function (a, b) {
      this.setData({
        total: a + b
      })
    }
  },
  
  methods: {
    updateData() {
      this.setData({
        a: this.data.a + 1,
        b: this.data.b + 1
      })
    }
  }
})

 

 

Mobx 与 Computed 结合使用

1. 使用旧版 API

- 自定义组件仍然使用 Component 方法构建组件,将两个扩展依赖包的使用全部改为旧版 API

- [mobx-miniprogram-bindings 官方文档](https://www.npmjs.com/package/mobx-miniprogram-bindings)
- [miniprogram-computed 官方文档](https://www.npmjs.com/package/miniprogram-computed)

 

2. 使用兼容写法

- 即要么使用 ComponentWithStore 方法构建组件,要么使用 ComponentWithComputed 方法构建组件

- 如果使用了 ComponentWithStore 方法构建组件,计算属性写法使用旧版 API
- 如果使用了 ComponentWithComputed 方法构建组件,Mobx写法使用旧版 API

 

如果使用了 ComponentWithStore 方法构建组件,计算属性写法使用旧版 API 

import { ComponentWithComputed } from 'miniprogram-computed'

// component.js
const computedBehavior = require('miniprogram-computed').behavior

ComponentWithStore({
  behaviors: [computedBehavior],

  data: {
    a: 1,
    b: 1,
    sum: 2
  },
    
  watch: {
    'a, b': function (a, b) {
      this.setData({
        total: a + b
      })
    }
  },
    
  computed: {
    total(data) {
      // 注意: computed 函数中不能访问 this ,只有 data 对象可供访问
      // 这个函数的返回值会被设置到 this.data.sum 字段中
      return data.a + data.b + data.sum // data.c 为自定义 behavior 数据段
    }
  },
    
  // 实现组件和 Store 的关联
  storeBindings: {
    store: numStore,

    // fields 和 actions 有两种写法:数组写法 和 对象写法

    // 数组写法
    fields: ['numA', 'numB', 'sum'],
    actions: ['update']
  }
})

 

使用了 ComponentWithComputed方法构建组件,Mobx写法使用旧版 API

import { ComponentWithComputed } from 'miniprogram-computed'

// 导入 storeBindingsBehavior 方法实现组件和 Store 的关联
import { storeBindingsBehavior } from "mobx-miniprogram-bindings"
// 导入 Store 
import { numStore } from '../../stores/numstore'


ComponentWithComputed({
  behaviors: [storeBindingsBehavior],

  data: {
    a: 1,
    b: 1,
    sum: 2
  },
  watch: {
    'a, b': function (a, b) {
      this.setData({
        total: a + b
      })
    }
  },
  computed: {
    total(data) {
      // 注意: computed 函数中不能访问 this ,只有 data 对象可供访问
      // 这个函数的返回值会被设置到 this.data.sum 字段中
      return data.a + data.b + data.sum // data.c 为自定义 behavior 数据段
    }
  },
    
  // 实现组件和 Store 的关联
  storeBindings: {
    store: numStore,

    // fields 和 actions 有两种写法:数组写法 和 对象写法

    // 数组写法
    fields: ['numA', 'numB', 'sum'],
    actions: ['update']
  }
})

 

标签:03,数据通信,微信,js,miniprogram,组件,import,data,computed
From: https://www.cnblogs.com/MingQiu/p/18154721

相关文章

  • 数据通信
    串行和并行通信串行通信和并行通信都是计算机科学中的概念,指的都是计算机内部或者计算机与外设之间的通信方式。串行通信:Serialcommunication,是指使用一条数据线(另外需要地线,可能还需要控制线),将数据一位一位地依次传输。并行通信:Parallelcommunication,是指使用多条数据线,同时......
  • AP5103 是一款效率高,稳定可靠的 LED 灯恒流驱动控制芯片
    产品描述AP5103是一款效率高,稳定可靠的LED灯恒流驱动控制芯片,内置高精度比较器,固定关断时间控制电路,恒流驱动电路等,特别适合大功率LED恒流驱动。AP5103采用ESOP8封装,散热片内置接SW脚,通过调节外置电流检测的电阻值来设置流过LED灯的电流,支持外加电压线性调光,最大电......
  • 【专题STM32F03】FreeRTOS 队列queue传递结构体,野火例程代码简单修改。
    /************************************************************************@filemain.c*@authorfire*@versionV1.0*@date2018-xx-xx*@briefFreeRTOSV9.0.0+STM32消息队列******************************************************......
  • centos8报错错误:为 repo 'appstream' 下载元数据失败 : Cannot prepare internal mirr
    出现如下错误的错误:为repo‘appstream’下载元数据失败:Cannotprepareinternalmirrorlist:NoURLsinmirrorlist原因在2022年1月31日,CentOS团队终于从官方镜像中移除CentOS8的所有包。CentOS8已于2021年12月31日寿终正非,但软件包仍在官方镜像上保留了一段时间。现在......
  • L3-037 夺宝大赛
    原题链接\(code\)#include<bits/stdc++.h>usingnamespacestd;intdis[105][105];intxx[4]={1,0,-1,0},yy[4]={0,1,0,-1};inta[105][105];intvis[105][105]={0};structnode{intx,y;};map<int,int>cnt;map<int,int>ren;intmain......
  • 无root权限,解决conda环境的报错ImportError: /lib/x86_64-linux-gnu/libstdc++.so.6:
    网上的方法都需要sudo或者root权限,但是服务器多是实验室公用,没有ruuto权限,因此更好的办法是通过conda只改自己虚拟环境的环境变量。问题原因问题的根本原因是Linux系统没有GLIBCXX_3.4.30动态链接库。这个库和gcc版本有关。因此要么你更换版本,要么找一个别的so链接到这个连接......
  • 用户下单+微信支付学习记录
    开始之前补充两个知识点,因为之前写mapper.xml文件中sql语句时,没有提示功能就会很麻烦,补充了此功能:IDEAsql自动补全/sql自动提示/sql列名提示_idea提示sql语句-CSDN博客查看类源码:ctrl+shift+/,查看方法详情:ctrl+mouse1用户下单 接口设计     直接看过了,手动导......
  • feign调用接口报错No qualifying bean of type '***HttpMessageConverters' available
    在整合springcloudgeateway时,调用了feign接口,报错Noqualifyingbeanoftype'org.springframework.boot.autoconfigure.http.HttpMessageConverters'available报错信息feign.codec.EncodeException:Noqualifyingbeanoftype'org.springframework.boot.autocon......
  • 微信小程序canvas2d实现可滑动的圆环形进度条
     最近在搞一个微信小程序,有一个圆环的进度条,而且要求颜色要渐变的,本来想用秋云插件实现,但是秋云的插件不能滑动这个进度条,后面用canvas实现成品效果图:避坑:  <canvasid="myCanvas"type="2d"></canvas><canvascanvas-id="myCanvas"></canvas>两个canvas标签,一......
  • 使用FAL操作STM32F103VET6单片机的片内flash和外部norflash(SFUD驱动)
    1.新建一个命名为fal的工程,控制台串口我使用了uart5,对应管脚PC12和PD2工程新建好以后,编译,报错双击改报错信息,跳转到下图这个位置 把RT_WEAK改为rt_weak,后重新编译,下载到单片机中重新正常运行2.双击CubeMXSettings,选择正确的单片机型号,配置norflash使用的SPI......