ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 如何给由组件触发的事件中传入自定义的参数 ### 业务场景1 1. 以简单的轮播图为例,这个功能几乎在所有的移动端应用里都会有,是个很好的例子。 ```jsx <template> <div> <u-swiper keynName="image" height=”325rpx" :list="SwiperList" /> </div> </template> <script> export default { data() { return { SwiperList: [ { id: 1, image: 'https://images.unsplash.com/photo-1648737154547-b0dfd281c51e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80', title: '图片1', url: '/pages/category/category?id=1' }, { id: 2, image: 'https://images.unsplash.com/photo-1648737154547-b0dfd281c51e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80', title: '图片2', url: '/pages/category/category?id=2' } ] } } } </script> ``` 以上这段代码就可以为我们的应用添加轮播图了,但是实际上的需求往往并不是这么简单。 例如:希望用户点击轮播图以后可以跳转到指定的链接(通过url给出) 很自然的,根据文档,我们找到轮播图组件有一个点击事件,我们可以利用它来实现这个需求。 ```jsx <template> <div> <u-swiper keynName="image" height=”325rpx" :list="SwiperList" @click="onClickSwiper" /> </div> </template> <script> export default { methods: { onClickSwiper(index) { // 组件回调中会给我们点击的index let url = this.SwiperList[index].url; uni.navigateTo({ url, fail: e => console.log(e); }) } } } </script> ``` 这段代码可以很好的工作,能够满足业务场景下的需求。但是通常情况下,首页不止有轮播图,而可能还有被称为《金刚区》的快捷导航菜单区域,通常需要这些区域也是可点击的,当然你可以再写一个onClickQuickNav函数来单独处理这个逻辑(而且会工作的很好),但是我们能不能写一个通用的函数来解决这个页面的需求呢? 所以我们封装函数如下: ```jsx export default { methods: { onNavigate(url = '') { if(typeof url !== 'string' || url === '') { console.error(’url必填‘); return; } uni.navigateTo({ url, fail: e => { console.error(`跳转失败,理由是: ${e.errMsg}`) } }) } } } ``` 现在函数非常简单的接受一个字符串,原本的调用方式会直接报错,我们如何能够仅靠这个函数来满足业务场景需求呢?这就是本题的关键:对于由组件触发的事件中,我们能不能有机会在调用我们的methods的之前适当的装饰参数呢? 当然是有的,现在来逐一讲解: #### 方案1: $event 我们来摘抄官方文档的一段话: ![image-20220407134853748](https://qiniu.buaihechengzizhi.com/img/image-20220407134853748.png) > Sometimes we also need to access the original DOM event in an inline statement handler. You can pass it into a method using the special `$event` variable: 这段话的意思是说,有时候我们希望能够在内联v-on里访问DOM的原生事件对象,你可以使用$event这个特别的关键字来表示它。 所以我们可以把代码改造如下: ```jsx <template> <div> <u-swiper keynName="image" height=”325rpx" :list="SwiperList" @click="onNavigate(SwiperList[$event].url)" /> </div> </template> ``` 但是这个方案在部分平台可能不会如预期那样工作,现在我们来讲解第二种方案。 #### 方案2: 内联的减头函数 这里的关键点是,箭头函数可以直接作为js表达式来给vue使用。我们直接来看例子: ```jsx <template> <div> <u-swiper keynName="image" height=”325rpx" :list="SwiperList" @click="index => onNavigate(SwiperList[index].url)" /> </div> </template> ``` 这其实等价于如下写法: ```vue <template> <div> <u-swiper keynName="image" height=”325rpx" :list="SwiperList" @click="wrapper" /> </div> </template> <script> export default { methods: { wrapper(index) { this.onNavigate(this.SwiperList[index].url); } } } </script> ``` 只不过这么写很呆而已。 > PS: 通常你应该选择方案2(内联的箭头函数),方案1($event访问原始参数)的平台兼容性并没有想象的好 ### 业务场景2 参考GitHub issues: [建议将Checkbox name属性类型增加一个Object · Issue #292 · umicro/uView2.0 (github.com)](https://github.com/umicro/uView2.0/issues/292) > 本文作者: 不爱喝橙子汁