事件代理:父子组件传值
含义:将子元素的事件通过冒泡的形式交由父元素来执行
原理:事件委托是利用事件的冒泡原理来实现的
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>