Vue3渲染函数:如何让应用替换根元素而非挂载到其innerHTML中?
解决Vue3挂载时替换根元素而非其innerHTML的问题
Vue3的app.mount()默认会把内容渲染到目标元素的innerHTML里,而Vue2是直接替换目标元素本身。要模拟Vue2的行为,可以通过以下方法实现:
直接操作DOM替换
核心思路是先把Vue应用挂载到一个临时元素上,再用挂载后的真实DOM替换掉原来的目标元素:
import { createApp, h } from 'vue'; import ContentApp from '@js/ContentApp'; // 获取目标根元素 const targetEl = document.getElementById('vueContent'); // 创建应用并挂载到临时div const app = createApp({ render: () => h(ContentApp, { /* 你的props */ }), }); app.use(store); const vm = app.mount(document.createElement('div')); // 复制原元素的属性(如果需要保留id、class等) Array.from(targetEl.attributes).forEach(attr => { vm.$el.setAttribute(attr.name, attr.value); }); // 替换原元素 targetEl.replaceWith(vm.$el);
封装成通用工具函数
如果项目中有多处需要这种挂载方式,可以封装成工具函数复用:
// 工具函数:模拟Vue2的挂载替换行为 function mountAsReplace(el, app) { const targetEl = typeof el === 'string' ? document.querySelector(el) : el; if (!targetEl) return null; // 挂载到临时元素 const vm = app.mount(document.createElement('div')); // 复制原元素属性 Array.from(targetEl.attributes).forEach(attr => { vm.$el.setAttribute(attr.name, attr.value); }); // 替换原元素 targetEl.replaceWith(vm.$el); return vm; } // 使用示例 const app = createApp({ render: () => h(ContentApp, { /* props */ }), }); app.use(store); mountAsReplace('#vueContent', app);
这样处理后,最终的DOM结构就会和Vue2挂载时一致,直接替换掉#vueContent元素,而不是渲染到它内部。
内容的提问来源于stack exchange,提问作者Olie Cape
相关产品推荐
相关产品推荐

