Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

自定义指令 #8

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 47 additions & 4 deletions src/components/HelloWorld.vue
Original file line number Diff line number Diff line change
@@ -1,23 +1,66 @@
<template>
<div class="hello" data-spma="aa">
<div ref="rootCompRef" class="hello" data-spma="aa" >
<span>show spm:{{spmText}}</span>
<div data-spmb="bb">
<button data-spmc="cc">Click it</button>
<div data-spmb="bb" >
<button data-spmc="cc" v-spmclick="handleClick">Click it</button>
</div>
<div data-spmb="dd">
<button data-spmc="ff">Click it</button>
<button data-spmc="ff" v-spmclick="handleClick">Click it</button>
</div>
</div>
</template>

<script>
// 获取所有spm 开头的值
function getSPMFromObject(o) {
if(!o) return;
if(typeof o !== 'object') return;
const reg = /^spm./;
for(let key in o) {
if(reg.test(key)){
return o[key];
}
}
}

function gainAllParentNodeDataSet(el, fn= () =>{}) {
const ary = [];
let currentEl = el;
while(currentEl) {
let spmc = getSPMFromObject(currentEl?.dataset);
if(spmc){
ary.unshift(spmc);
}
currentEl = currentEl.parentNode;
}
fn(ary.join('.'));
}

const spmclick = {
mounted: (el, binding) => {
el.handler = gainAllParentNodeDataSet.bind(null, el, binding.value);
el.addEventListener('click', el.handler)
},
unmounted: (el) => {
el.removeEventListener('click', el.handler);
}
}

// TODO 利用事件代理实现一个简单的收集spm信息的方法,注意不是针对每一个按钮进行函数绑定。场景:考虑一下如果一个页面中有很多按钮,需要如何处理
export default {
name: 'HelloWorld',
data: ()=>{
return {
spmText: 'xx.xx.xx'
}
},
methods: {
handleClick(spmText) {
this.spmText = spmText
},
},
directives: {
spmclick // 自定义指令实现
}
}
</script>
Expand Down
Loading