vuejs2 - Vue.js : what's the difference between <component :is ="comp-name"/> and <div :is ="comp-name"/>?

标签 vuejs2 vue-component

在vue中使用动态组件时,我们可以使用component或 html 标签,例如 div作为标签名称:

<component :is="comp-name"></component>

或者:
// assume that the root tag of comp-name is div
<div :is="comp-name"></div>

那么这两种方式有什么区别呢?是相同的?

最佳答案

is ”属性不是特定于 Vue 的,它来自自定义元素规范。

另见 What is HTML "is" attribute?

但显然 Vue 必须自己实现它以进行编译,模仿自定义元素规范。

在您展示的示例中,我想这无关紧要,因为在这两种情况下,标签( <component><div> )都将被 Vue 组件实例替换。这是使用is的典型情况在几个可能的组件(“动态组件”)之间切换的属性。

然而,当您尝试在某些 HTML 元素中使用自定义元素/Vue 组件(带有运行时编译)时,这些元素限制了它们可以拥有的子元素的类型,这开始变得重要,如 DOM Template Parsing Caveats 中所述。 Vue指南的部分:

Some HTML elements, such as <ul>, <ol>, <table> and <select> have restrictions on what elements can appear inside them, and some elements such as <li>, <tr>, and <option> can only appear inside certain other elements.



在这些情况下,is属性可能不(仅)用于在动态组件之间切换,而是为了遵守 HTML 限制(以避免浏览器对我们的自定义组件做出意外行为),同时稍后仍由我们的自定义组件替换它们。

这是一个带有 <table> 的快速演示:

Vue.component('my-row', {
  template: '#my-row',
});

new Vue({
  el: '#app',
});
td,
th {
  border: 1px solid black;
}
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <table id="table1">
    <tr>
      <th>Table</th>
      <td>1</td>
    </tr>
    <!-- Below Custom component will be stripped out of the table. Exact result may differ depending on browsers -->
    <my-row></my-row>
  </table>

  <hr />

  <table id="table2">
    <tr>
      <th>Table</th>
      <td>2</td>
    </tr>
    <!-- Valid TR row will be correctly replaced by Custom component -->
    <tr is="my-row"></tr>
  </table>
</div>

<template id="my-row">
  <tr>
    <th>Header</th>
    <td>Cell</td>
  </tr>
</template>


结果:
  • 在 Firefox 中,<my-row>标签呈现在 <table> 的外部和上方.
  • 在 Chrome 中相同。
  • 关于vuejs2 - Vue.js : what's the difference between <component :is ="comp-name"/> and <div :is ="comp-name"/>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50619025/

    相关文章:

    javascript - Vue.js:添加 v-on:click 时按钮消失

    javascript - "Unexpected token <"用于使用 Webpack 运行的 VueJS

    javascript - 在列表组 bootstrap vue js 中仅调用子按钮而不调用父按钮

    javascript - 在 data() 函数和 v-model 中我应该做什么?

    forms - Vuelidate 未正确验证表单数据

    javascript - 输入上的 v-model 通过其他脚本动态更改值?

    javascript - 找到更好的方法来查看对象是否已填充字段

    javascript - 如何在 select 中添加条件? (Vue.JS 2)

    javascript - 如何在 Vue.js 方法中使用外部 JavaScript 对象

    javascript - 在数据中创建假 $route