下面是修正后的代码示例,展示了如何正确地使用 uni.$emit() 来触发自定义事件,并且如何传递事件名称和参数:
onSwiperChange(e) {
// 获取当前滑动项的索引
var currentIndex = e.detail.current;
console.log('当前滑动项的索引:', currentIndex);
// 假设您希望触发的事件名称是 'swiper-change',并且传递当前索引作为参数
this.$emit('swiper-change', currentIndex);
// 如果您需要在父组件中根据不同的索引执行不同的操作,您可以在父组件中监听这个事件
// 并在事件处理函数中根据传递的索引值来执行不同的逻辑
},
在子组件中,您可以这样监听并处理这个自定义事件:
export default {
// ... 其他选项 ...
methods: {
handleSwiperChange(index) {
console.log('接收到滑动变化事件,当前索引:', index);
if (index === 1) {
// 执行事件1的逻辑
} else if (index === 2) {
// 执行事件2的逻辑
}
// ... 其他逻辑 ...
}
},
mounted() {
// 在子组件中监听自定义事件 'swiper-change'
this.$on('swiper-change', this.handleSwiperChange);
},
beforeDestroy() {
// 在组件销毁前移除事件监听
this.$off('swiper-change', this.handleSwiperChange);
}
// ... 其他选项 ...
};
请注意,上述代码中的 this. o n 和 t h i s . on 和 this. on和this.off 分别用于在子组件中监听和移除自定义事件。在 beforeDestroy 生命周期钩子中移除事件监听是一个好习惯,可以避免内存泄漏。