是:“=10=”“=12=”与“=11=”

Vue: <tag></tag> vs <tag />

正如我在标题中简要说明的那样,我想知道在 Vue 中编写 self-closing 标签是否符合常规 and/or 合法。

在文档中,我看到了打开和关闭标签,但我在其他地方看到作者将组件写成自关闭标签,比如 <some-component />

问题分为两部分:

Components with no content should be self-closing in single-file components, string templates, and JSX - but never in DOM templates.

来自 Vue 风格指南。

它是合法的,被 vue 风格指南强烈推荐。 Vue Style Guide #self-closing components

以上两个问题都已回答。但是,我想指出自闭标签中没有内容到底是什么意思。

  1. 当我们使用<div><p>Something</p></div>时,<p>标签是内容,因此我们不能使用div作为自闭标签。

  2. 与 Vue JS 组件类似,您也可以在组件标签中包含内容。例如,<MyComponent><p>Something Else</p></MyComponent>。 然后,在 <MyComponent> 的组件定义中,您必须包含以呈现使用 <MyComponent> 的任何地方传递的内容。

  3. 如果您不打算从 <MyComponent> 传递任何内容。也就是说,如果您的组件定义中没有 <slot> 标签,那么您的 <MyComponent> 可以是一个自闭标签。