简体   繁体   English

Vue 替换“el”组件而不是在其中渲染?

[英]Vue replacing "el" component instead of rendering inside it?

I don't know if this is a standard feature but Vue is replacing the element specified by "el" when the instance is created, instead of rendering inside of it.我不知道这是否是标准功能,但 Vue 在创建实例时替换了“el”指定的元素,而不是在其中渲染。

if I use an id to reference the "el" then it works fine.如果我使用 id 来引用“el”,那么它可以正常工作。 ie, IE,

new Vue({el: "div#app", render: h => h("span", {}, "Hello World")})

which will render as:这将呈现为:

<body><div id="app"><span>Hello World</span></div></body>

but if I use a JS Element object as "el" then it replaces that element altogether.但如果我使用 JS 元素 object 作为“el”,那么它会完全替换该元素。

const divElement = document.querySelector("div#app");
new Vue({el: divElement, render: h => h("span", {}, "Hello World")});

will render as:将呈现为:

<body><span>Hello World</span></body>

is it supposed to do that, or am I doing something wrong?它应该这样做,还是我做错了什么?

Probably there is some confusion on your side.可能你这边有些困惑。 I just prepared a sample where:我刚刚准备了一个样本,其中:

const el = document.getElementById("app");
new Vue({ el: el, render: (h) => h(App) });

Successfully renders to:成功渲染到:

<body><div id="app">// content here</div></body>

https://codesandbox.io/s/clever-swartz-yie0l?file=/src/main.js https://codesandbox.io/s/clever-swartz-yie0l?file=/src/main.js

But you still need to keep in mind that is not an element of DOM you had before vue mounted there but a virtual representation of it.但是您仍然需要记住,这不是您在安装 vue 之前拥有的 DOM 元素,而是它的虚拟表示。

From vue documentation:来自 Vue 文档:

The provided element merely serves as a mounting point.提供的元件仅用作安装点。 Unlike in Vue 1.x, the mounted element will be replaced with Vue-generated DOM in all cases.与 Vue 1.x 不同,挂载的元素在所有情况下都将替换为 Vue 生成的 DOM。 It is therefore not recommended to mount the root instance to or.因此不建议将根实例挂载到 or 上。

https://v2.vuejs.org/v2/api/#el https://v2.vuejs.org/v2/api/#el

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM