Vue 中使用的 inheritAttrs: false 和 $attrs 是什么? [英] What are inheritAttrs: false and $attrs used for in Vue?

查看:91
本文介绍了Vue 中使用的 inheritAttrs: false 和 $attrs 是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如问题所暗示的那样,我无法弄清楚它们的含义以及为什么要使用它.据说可以用它,这样当我们有很多组件,我们想从父组件传递数据到子组件的子组件时,我们不必使用道具.这是真的吗?

如果你能提供一个更简单的例子就好了.Vue.js 文档没有提及太多.

解决方案

查看 "禁用属性继承" 部分文档和 api 说明 了解完整详情.

它的主要用途是定义传递属性的所谓透明"组件.文档中给出的示例是一个包装 input 元素的组件:

//组件Vue.component('基本输入', {继承属性:假,道具:['标签','价值'],模板:`<标签>{{ 标签 }}<输入v-bind="$attrs"v-bind:value="value"v-on:input="$emit('input', $event.target.value)">`})//用法<基本输入v-model="用户名"必需的placeholder="输入您的用户名"/>

requiredplaceholder 属性然后设置在 input 而不是包装 label 上.>

它与组件子级的子级没有任何关系,但可以在这样的层次结构中使用.

我希望这可以为您解决问题.

As the question suggests, I can't figure out their meaning and why I should use it. It's said that it can be used so that when we have many components and we want to pass data from parent to the child's child's child's component, we don't have to use props. Is this true?

It'd be nice If you could provide an easier example. Vue.js docs don't mention much on it.

解决方案

Have a look at the "Disabling Attribute Inheritance" section of the docs and the api description for the full details.

It's main usage is to define so-called "transparent" components that pass-through attributes. The example given in the doc is a component wrapping an input element:

// Component
Vue.component('base-input', {
  inheritAttrs: false,
  props: ['label', 'value'],
  template: `
    <label>
      {{ label }}
      <input
        v-bind="$attrs"
        v-bind:value="value"
        v-on:input="$emit('input', $event.target.value)"
      >
    </label>
  `
})

// Usage
<base-input
  v-model="username"
  required
  placeholder="Enter your username"
/>

The required and placeholder attributes are then set on the input instead of the wrapping label.

It doesn't really have anything to do with children of children of components but it can be used in such a hierarchy.

I hope that clears things up for you.

这篇关于Vue 中使用的 inheritAttrs: false 和 $attrs 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆