vue中事件代理的使用

事件代理: 利用事件冒泡的原理(事件会向它的父级一级传递),把事件加到父级上,通过判断事件来源,执行相应的子元素的操作,可以极大减少事件绑定次数,提高性能;也可以让新加入的子元素也可以拥有相同的操作。
html5中添加了新属性data-xxx 可以用来存储数据

  • 例子: 三个按钮,单击的时候激活展示
  • 常规做法: 通过子组件绑定事件,修改父组件的curIndex
  • 事件代理: 对父组件添加绑定事件(具体如下)
// 父组件
<template>
  <div  @click="handle($event)">
    <my-button
      :buttonStyle="buttonStyle"
      v-for="(item, index) in subjects"
      :key="index"
      :curIndex="curIndex"
      :index="index"
      :item="item"
      >{{ item }}
      </my-button >
  </div>
</template>
<script>
export default {
  name: "app",
  data() {
    return {
      curIndex: 0,
      buttonStyle: "",  // 动态添加类样式
      subjects: ["vue", "react", "angular"],
    };
  },
  methods: {
    handle(e) {
      let target = e.target; 
      if(target.className === 'btn-main') {
            this.curIndex = parseInt( target.dataset.index)  // e.target.dataset可以获取子组件中data-xxx对应的值
  	  }
  },
};
</script>
<style lang="scss">
  #app{
 	display: flex
   }
</style>

// 子组件
<template>
  <div>
  	// 通过data-xxx 动态添加数据
    <button :class="['btn-main', buttonStyle, curIndex === index ?  'btn-active':'']" :data-index='index'>
      <slot></slot>
    </button>
  </div>
</template>

<script>
export default {
    name: 'MyButton',
    props: {
      buttonStyle: String,
      item: String,
      index: Number,
      curIndex: Number
    },
};
</script>

<style lang="scss" scoped>
.btn-main {
    margin-right: 4px;
    width: 120px;
    height: 60px;
    padding: 4px;
    background: rgb(165, 80, 94);
    color: white;
    font-size: 20px;
}
.btn-danger {
  background: red;
}
.btn-success {
  background: green;
}
.btn-active {
  background: rgb(11, 172, 19);
}
</style>


你可能感兴趣的:(vue,vue.js,前端,javascript)