MutationObserver can not specific those doms create by Vue #10507
Replies: 5 comments 4 replies
-
come on Dai lo !! I need your help !!! 🥶 |
Beta Was this translation helpful? Give feedback.
-
demo链接打开,提示”代码不存在“😢 |
Beta Was this translation helpful? Give feedback.
-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
// 函数来设置输入元素的字体样式
function updateInputStyle(inputElement) {
const value = inputElement.value.toLowerCase(); // 转换为小写以便检查
if (value.includes('i') || value.includes('l')) {
inputElement.style.color = 'red'; // 字体颜色变红
inputElement.style.fontWeight = 'bold'; // 字体加粗
} else {
inputElement.style.color = ''; // 重置字体颜色
inputElement.style.fontWeight = ''; // 重置字体粗细
}
}
// 函数来添加事件监听器到input元素
function addInputListener(inputElement) {
console.log(inputElement);
inputElement.addEventListener('input', function() {
updateInputStyle(inputElement);
});
}
// 创建一个MutationObserver来观察DOM的变化
const observer = new MutationObserver((mutations) => {
console.log("come in mutationOb", mutations)
mutations.forEach(mutation => {
if (mutation.type === 'childList') {
mutation.addedNodes.forEach(node => {
if (node.tagName?.toLowerCase() === 'input') {
addInputListener(node);
}
});
}
});
});
// 配置观察器选项以观察子节点的变化
const config = { childList: true, subtree: true, attributes: true };
// 启动观察器以监听整个文档的变化
observer.observe(document.body, config);
const { createApp, h, ref } = Vue
const doms = [];
const appendInput = ()=>{
return h('input', ({ class:"tag", placeholder:"test" }))
}
setTimeout(()=>{
doms.push(appendInput());
doms.push(appendInput());
doms.push(appendInput());
createApp(h('div', doms)).mount("#app");
},2000);
</script>
<body>
<div class="box">
<input placeholder="demo"/>
</div>
<div id='app'></div>
</body>
</html> |
Beta Was this translation helpful? Give feedback.
-
Vue adds the inputs as children to the div before that div is inserted to the DOM. So the MutationObserver only sees one Mutation: the div being inserted. Vue does it this way to make updates more performant. |
Beta Was this translation helpful? Give feedback.
-
Put DOM operations in mounted hooks. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
https://code.juejin.cn/pen/7345741590483599397
see this demo
how to serveal that。it seems to be related to Vue using innerHTML to create dom。
Beta Was this translation helpful? Give feedback.
All reactions