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

spm collection using hook #21

Open
wants to merge 1 commit 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
16 changes: 5 additions & 11 deletions src/components/HelloWorld.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<template>
<div class="hello" data-spma="aa">
<span>show spm:{{spmText}}</span>
<span>show spm:{{ spmText }}</span>
<div data-spmb="bb">
<button data-spmc="cc">Click it</button>
</div>
Expand All @@ -10,16 +10,10 @@
</div>
</template>

<script>
// TODO 利用事件代理实现一个简单的收集spm信息的方法,注意不是针对每一个按钮进行函数绑定。场景:考虑一下如果一个页面中有很多按钮,需要如何处理
export default {
name: 'HelloWorld',
data: ()=>{
return {
spmText: 'xx.xx.xx'
}
}
}
<script setup>
import useSpm from "./useSpm.vue";

let { spm: spmText } = useSpm();
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
Expand Down
48 changes: 48 additions & 0 deletions src/components/useSpm.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<script>
import { onMounted, onUnmounted, ref } from "vue";

export default function useSpm() {
let spm = ref("");

const addClickEvent = (e) => {
spm.value = getSpmData(e.target).join(".");
};

const getCurrentSpm = (current) => {
const ds = current.dataset;
for (let key in ds) {
if (key.startsWith("spm")) {
return ds[key];
}
}
};

const getSpmData = (target) => {
const spmList = [];
let next = target;
const rootEl = document.querySelector("#app");

while (next && !next.isEqualNode(rootEl)) {
const val = getCurrentSpm(next);
if (val) spmList.unshift(val);
next = next.parentNode;
}

return spmList;
};

// on mounted add event listener
onMounted(() => {
console.log("on mounted");
window.addEventListener("click", addClickEvent);
});

// on unmounted remove event listener
onUnmounted(() => {
console.log("on unmounted");
window.removeEventListener("click", addClickEvent);
});

return { spm };
}
</script>