效果如下:
事件委託:也稱事件代理
原理:事件委託就是利用事件冒泡,指定一個事件處理程序,就可以管理這一類型的所有事件。
應用場景:我有一個ul標籤,下面有很多li標籤,每個li標籤都需要添加事件,難道我們要獲取每個li然後在添加事件嗎? 這樣太浪費內存了,也不利於網頁性能優化,我們要儘可能減少dom操作,所以我們能不能只給ul添加點擊事件,然後利用事件冒泡,這樣每個li標籤都有事件了.
效果的代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
#beta ul li {
display: inline-block;
width: 40px;
background-color: #3cc3bd;
margin-left: 10px;
text-align: center;
cursor: pointer;
color: #fff;
}
#beta ul li.variation {
background-color: #fd5262;
}
</style>
<!-- 通過cdn引入vue.js -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="beta">
<ul @click="entrust">
<li
v-for="(item,index) in dataList"
:key="index"
:data-index="index"
:data-item="item.name"
:class="{variation: pitchOn == index}"
>
{{ item.name }}
</li>
</ul>
</div>
</body>
<script>
new Vue({
el: '#beta',
data: {
message: '',
pitchOn: 0,
dataList: [
{
name: '趙雲'
},
{
name: '韓信'
},
{
name: '劉禪'
},
{
name: '貂蟬'
},
{
name: '李白'
}
]
},
methods: {
entrust(e) {
var dom = e.target
var index = dom.getAttribute('data-index')
// 當點擊到按鈕外時,不執行
if (index !== null) {
var item = dom.getAttribute('data-item')
this.pitchOn = index
console.log('我的下標爲:', index, '對應的值爲:', item)
}
}
}
})
</script>
</html>
部分解析:
1.在vue中可以直接給ul 添加點擊事件, vue框架會自動生成事件委託
2.如果想要獲取點擊的li 標籤,只需要在標籤屬性上添加一個data-xxx,再通過getAttribute獲取值就可以了