程序员

在vue中使用inheritAttrs实现组件的扩展性介绍

作者:admin 2021-06-28 我要评论

1、首先我们创建一个input组件 template div class="inputCom-wrap" input v-bind="$attrs" / /div/template script lang="ts"import { defineComponent } from ...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

1、首先我们创建一个input组件

<template>
 <div class="inputCom-wrap">
 <input v-bind="$attrs" />
 </div>
</template>
 
<script lang="ts">
import { defineComponent } from 'vue'
 
export default defineComponent({
 inheritAttrs:false,//不希望根直接继承特性,而是使用$attrs自定义继承,当前组件的根就是inputCom-wrap
 setup () {
 return {}
 }
})
</script>
 
<style scoped> 
</style>

2、使用组件的时候,随便增加一些属性,如

<inputCom type="text" class="input-a"></inputCom>

<inputCom type="password" class="input-b"></inputCom>

3、查看最终的渲染结果为(与props不会冲突)

补充知识:vue组件深层传值inheritAttrs、$attrs、$listeners

1、$attrs

组件深层传值 可通过父组件绑定 v-bind="$attrs"传给子组件

一般子组件this.$attrs可以拿到父组件的所有传输的属性。

当子组件props注册了声明某属性之后,this.$attrs将不包含该属性;

同理通过v-bind="$attrs"绑定孙子组件也不会包含子组件props声明的属性。

props: {
 data:{
 type: Array,
 default: () => [],//数组格式[{label:xx,value:xxx}]
 }, 
 value: {
 type: Array,
 default: () => [],//数组格式[xx,xx,xx]
 },
 maxHeight:{
 type:[String,Number],
 default:350,
 }
 },

mounted() {
 console.log("来自多选",this.$attrs)

 },

2、inheritAttrs

默认值为true

默认情况子组件props未声明,父组件传输的其他属性会被认作 props 的 attribute 绑定 (attribute bindings) 将会“回退”且作为普通的 HTML attribute 应用在子组件的根元素上(有可能会覆盖子组件根元素上的某些属性列如 type="text"之类属性)

子组件的inheritAttrs 设置为false可以避免

3、$listeners

父组件-子组件-孙子组件,现在我要你在孙子组件里改变父组件的值,子组件直接绑定

<muti-select v-bind="$attrs" v-on="$listeners" class="select"></muti-select>

以上这篇在vue中使用inheritAttrs实现组件的扩展性介绍就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持站长技术。


原文链接:https://m.jb51.net/article/201555.htm

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • 阿里巴巴DevOps实践指南(八)| 以特性

    阿里巴巴DevOps实践指南(八)| 以特性

  • 阿里巴巴DevOps实践指南(五)| 业务驱

    阿里巴巴DevOps实践指南(五)| 业务驱

  • RISC-V工具链简介

    RISC-V工具链简介

  • 变局时代:RISC-V处理器架构的技术演变

    变局时代:RISC-V处理器架构的技术演变