【问题标题】:Parent attributes not working in Vue component父属性在 Vue 组件中不起作用
【发布时间】:2021-08-02 19:39:51
【问题描述】:

不确定这是否是默认行为,但我正在尝试在 Vue 中构建一个组件并尝试添加 id 和 class 等属性,但在呈现的代码中不存在。

组件

<template>
    <input type="text" name="hello" />
</template>

用法(命名为 md-input)

<md-input class="hello" />

<!-- this will render too wihtout the class attr -->
<input type="text" name="hello" />

【问题讨论】:

    标签: laravel vue.js vuejs3


    【解决方案1】:

    通常,属性被传递到组件的根元素上,如下所示 demo.

    但是当组件中有多个元素时就不会发生这种情况,并且您会在浏览器的控制台中看到警告:

    [Vue warn]: Extraneous non-props attributes (class) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. 
      at <MdInput class="hello" > 
      at <App>
    

    对于这种情况,您可以使用 v-bind="$attrs" 将任何属性绑定传递给内部 input

    <template>
      <label for="hello">My Input</label>
      <input type="text" name="hello" v-bind="$attrs" />
    </template>
    

    demo 2

    【讨论】:

      【解决方案2】:

      这是一个奇怪的行为,如果你在组件的模板上放置一个默认类呢?

      <template>
          <input type="text" name="hello" class="default" />
      </template>
      
      
      <md-input class="hello" />
      
      <!-- The element should be render like this --> 
      <input type="text" name="default hello" />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-03
        • 2019-10-24
        • 2021-05-23
        • 2017-06-28
        • 2020-03-29
        • 2020-04-18
        • 2017-08-20
        相关资源
        最近更新 更多