uni-app 事件传值this.$emit和uni.$emit

1.this.$emit

格式:this.$emit('事件',参数)

用于当子组件需要调用父组件的方法的场景下使用。

与之相对的当父组件需要调用子组件时则使用this.$refs的方法

示例

my-search.vue组件

<template>
  <view class="my-search-container" :style="{ 'background-color': bgcolor }" @click="searchBoxHandler">
    <view class="my-search-box" :style="{ 'border-radius': radius + 'px' }">
      <!-- 使用 uni-ui 提供的图标组件 -->
      <uni-icons type="search" size="17"></uni-icons>
      <text class="placeholder">搜索</text>
    </view>
  </view>
</template>

<script>
  export default {
    props: {
      // 背景颜色
      bgcolor: {
        type: String,
        default: '#C00000'
      },
      // 圆角尺寸
      radius: {
        type: Number,
        default: 18 // px
      }
    },
    data() {
      return {

      }
    },
    methods: {
      searchBoxHandler() {
        /// 调用子组件的名为click的方法
        this.$emit('click')
      }
    }
  }
</script>

<style lang="scss">

</style>

home.vue

<template>
  <view>
    <!-- 搜索组件 -->
    <view class="search-box">
      <my-search @click="gotoSearch"></my-search>
    </view>

  </view>
</template>

<script>
  
  export default {
    data() {

    },
    onLoad() {

    },
    methods: {
      gotoSearch() {
        // 跳转到另一个页面
        uni.navigateTo({
          url: '/subpkg/search/search'
        })
      }
    }
  }
</script>

<style lang="scss">

</style>

2.uni.$emit(eventName,OBJECT)

触发全局的自定义事件,附加参数都会传给监听器回调函数。

属性 类型 描述
eventName String 事件名
OBJECT Object 触发事件携带的附加参数

只要在想要传值的页面onload方法中注册订阅事件,在需要传值的页面传值就可以收到回调

onload(){
      //全局事件订阅,只要订阅了事件就可以收到值
    uni.$on("globleEvent",(rel)=>{
        console.log(rel)
    })
}

触发全局订阅事件的方法

//全局事件订阅只要注册的页面都可以收到回调值
uni.$emit("globleEvent","我是全局事件订阅的传值")

猜你喜欢

转载自blog.csdn.net/m0_63748493/article/details/126892823