Vue中自定义组件监听事件传参

自定义数字框组件如下

<template>
  <div class="count-box">
    <button @click="handleSub" class="minus">-</button>
    <input :value="value" @change="handleChange" class="inp" type="text">
    <button @click="handleAdd" class="add">+</button>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: Number,
      default: 1
    }
  },
  methods: {
    handleSub () {
      if (this.value <= 1) {
        return
      }
      this.$emit('input', this.value - 1)
    },
    handleAdd () {
      this.$emit('input', this.value + 1)
    },
    handleChange (e) {
      // console.log(e.target.value)
      const num = +e.target.value // 转数字处理 (1) 数字 (2) NaN

      // 输入了不合法的文本 或 输入了负值,回退成原来的 value 值
      if (isNaN(num) || num < 1) {
        e.target.value = this.value
        return
      }

      this.$emit('input', num)
    }
  }
}
</script>

<style lang="less" scoped>
.count-box {
  width: 110px;
  display: flex;
  .add, .minus {
    width: 30px;
    height: 30px;
    outline: none;
    border: none;
    background-color: #efefef;
  }
  .inp {
    width: 40px;
    height: 30px;
    outline: none;
    border: none;
    margin: 0 5px;
    background-color: #efefef;
    text-align: center;
  }
}
</style>

展示效果:
image

当父组件使用子组件时,例如绑定了监听事件@input,此时需要事件的value值和其他参数,一起使用,步骤应该如下:

   <!-- 数字框组件 即希望保留原本的形参,又需要通过调用函数传参 可以使用 箭头函数 改写-->
<CountBox :value="item.goods_num" @input="(value)=>changeCount(value,item.goods_id,item.goods_sku_id)"></CountBox>

需要用到箭头函数,代码中的 @input="(value)=>changeCount(item)" 中的箭头函数接收 value 参数,这是由事件触发时传递给 input 事件的值。另外,item 参数是由上下文传递给 changeCount 方法的。

在这种情况下,箭头函数的使用是为了确保函数内的 this 指向是正确的,因为箭头函数不会改变 this 的指向,而是继承自外层作用域的 this。

image

posted @   自学Java笔记本  阅读(101)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示