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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

gwenbi   2021-01-28 我要评论

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实现组件的扩展性介绍就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们