您当前的位置: 首页 > 

【03】

暂无认证

  • 2浏览

    0关注

    196博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

vue组件透传

【03】 发布时间:2021-03-20 10:33:15 ,浏览量:2

场景

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

主要按钮1
主要按钮2
主要按钮3

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



	默认按钮




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

c-van-button.vue


  
    
  



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

问题

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

默认按钮

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


  
    
  



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

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

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

使用inheritAttrs,vm. a t t r s , v m . attrs,vm. attrs,vm.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



  默认按钮1
  默认按钮2
  默认按钮3




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

c-van-button.vue


  
    
  



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

效果

总结

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

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

关注
打赏
1657344724
查看更多评论
立即登录/注册

微信扫码登录

0.0369s