vue组件透传

场景

当我们试使用某一组件库,或者其他不能修改或者不建议修改的组件时,
如vant的button组件,它默认type为default,我要让他type默认为primary的话,每次都要传入type参数

<van-button type="primary">主要按钮1</van-button>
<van-button type="primary">主要按钮2</van-button>
<van-button type="primary">主要按钮3</van-button>

那如果我想不传参数就让它type为primary的话,通常的做法就是再写个组件封装一下,如:
t4.vue

<template>
<div>
	<c-van-button>默认按钮</c-van-button>
</div>
</template>

<script>
import cVanButton from './c-van-button'
export default {
  name: "t4",
  components: {
    cVanButton
  }
}
</script>

c-van-button.vue

<template>
  <van-button :type="type">
    <slot/>
  </van-button>
</template>

<script>
export default {
  name: "c-van-button",
  inheritAttrs: false,
  props: {
    type: {
      type: String,
      default: 'primary'
    }
  }
}
</script>

问题

以上方法虽然简单的实现了type默认为primary,但是,如果需要在传入其他参数呢

<c-van-button size="large" loading>默认按钮</c-van-button>

c-van-button.vue是不是要这样写

<template>
  <van-button :type="type" :size="size" :loading="loading">
    <slot/>
  </van-button>
</template>

<script>
export default {
  name: "c-van-button",
  inheritAttrs: false,
  props: {
    type: {
      type: String,
      default: 'primary'
    },
    size: {
      type: String,
      default: 'normal'
    },
    loading: {
      type: Boolean,
      default: false
    }
  }
}
</script>

如果参数很多呢,是不是也要一个一个写呢

很显然,这并不是一个完美的解决方法

使用inheritAttrs,vm. a t t r s , v m . attrs,vm. attrsvm.listeners

什么是inheritAttrs


https://cn.vuejs.org/v2/api/#inheritAttrs

https://cn.vuejs.org/v2/api/#vm-attrs

https://cn.vuejs.org/v2/api/#vm-listeners

解决方案

t4.vue

<template>
<div>
  <c-van-button size="large" loading>默认按钮1</c-van-button>
  <c-van-button type="warning" size="small">默认按钮2</c-van-button>
  <c-van-button color="red">默认按钮3</c-van-button>
</div>
</template>

<script>
import cVanButton from './c-van-button'
export default {
  name: "t4",
  components: {
    cVanButton
  }
}
</script>

c-van-button.vue

<template>
  <van-button :type="type" v-on="$listeners" v-bind="$attrs">
    <slot/>
  </van-button>
</template>

<script>
export default {
  name: "c-van-button",
  inheritAttrs: false,
  props: {
    type: {
      type: String,
      default: 'primary'
    }
  }
}
</script>

效果

总结

通过对组件的二次封装,声明默认参数,对其他参数用v-on="$listeners" v-bind="$attrs"的形式传入,并且声明inheritAttrs: false

未声明inheritAttrs: false会同时将参数写入html自定义属性中

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值