使用事件代理:单选按钮 --点击添加样式

事件代理:父子组件传值

含义:将子元素的事件通过冒泡的形式交由父元素来执行

原理:事件委托是利用事件的冒泡原理来实现的

Event对象提供了一个属性叫target,可以返回事件的目标节点,我们称为事件源

也就是说,target就可以表示为当前的事件操作的dom,但是不是真正操作dom

页面文件

<template>
  <div class="">
    <btn-radios :subjects="subjects" />
  </div>
</template>

<script type="text/javascript">

// 实际引入的是:@/components/BtnRadios/index.vue 【自定义插件的入口文件】
import BtnRadios from '@/components/BtnRadios'

export default {
  name: 'BtnRadio',
  components: {
    BtnRadios
  },
  data () {
    return {
      subjects: [
        'Vue',
        'React',
        'Angular'
      ]
    }
  },

}
</script>

<style lang="less" scoped>
</style>

components / BtnRadio

子组件:Button.vue

<template>
  <button
    :class="['radio-btn', { current: index === curIndex }]"
    :data-index="index"
  >
    {{ item }}
  </button>
</template>

<script type="text/javascript">
export default {
  name: 'RadioBtn',
  props: {
    item: String,
    index: Number,
    curIndex: Number
  },
  data () {
    return {

    }
  }
}
</script>

<style lang="less" scoped>
.radio-btn {
  height: 34px;
  border: none;
  outline: none;
  padding: 0 15px;
  margin-right: 20px;
  border-radius: 5px;
  border: 1px solid #ddd;
  color: #999;
  background-color: #eee;
}
.current {
  border-color: red;
  color: red;
  background-color: #ffffff;
}
</style>

父组件:index.vue

BtnRadio组件的出口文件

<template>
  <div class="wrapper" @click="radioCheck($event)">
    <radio-btn
      v-for="(item, index) of subjects"
      :key="index"
      :index="index"
      :curIndex="curIndex"
      :item="item"
    />
  </div>
</template>

<script type="text/javascript">

import RadioBtn from './Button'

export default {
  name: 'Btn',
  props: {
    subjects: Array
  },
  components: {
    RadioBtn
  },
  data () {
    return {
      curIndex: 0
    }
  },
  methods: {
    // 点击事件
    radioCheck (e) {
        
      // 保存事件源对象
      const tar = e.target,
        className = tar.className;

      console.log(tar);
      // 结果例如:<button class="radio-btn current" data-index="1"></button>
      console.log(className); // 结果:radio-btn

      if (className === 'radio-btn') {
        // 通过子组件绑定自定义属性,父组件通过事件源对象获取绑定的属性
        const index = parseInt(tar.dataset.index);
        this.curIndex = index;
      }
    }
  }

}
</script>

<style lang="less" scoped>
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落花流雨

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值