vue组件封装之封装一个单选按钮

少小离家老大回,骚话学了一大堆。

前言

  我需要一个单选按钮,不知道是不是我眼瞎,ElementUI中没有找到我想要的那个组件。于是我就萌生了一种自己封装组件的念头。自己动手,丰衣足食,既然如此,那我就自己动手做一个呗。

相关代码放在这里:https://gitee.com/siumu/blog_code.git

问题与阻碍

要想封装一个组件,那么我们就会面临这几个问题。

  • 父子组件之间如何传值?
  • 如何在子组件中修改父组件的值?
  • 如何在父组件中使用 v-model 来绑定子组件的数据?

第一个问题还是比较好解决的,我们只需要在子组件中使用props这个属性,在props里面定义所需要的变量,就可以在父组件里通过v-bind将值传递给子组件了。

剩下两个问题也比较好解决,我们在子组件里使用this.$emit( event,val)函数,就可以触发父组件的事件,通过父组件的事件修改父组件里的那个值。

其中的 event就是事件名称,比如有input事件,click事件,change事件等等,val就是改变的值。v-model其实就是触发了父组件的input事件。

有了这些,那我们就可以自己封装组件来用了。

动手实践

我直接贴代码

<template>
  <div class="radio-btn">
    <span v-for="(item,index) in radioList" :key="index"
          class="radio-span"
          :class="{'radio-span-active': value === item.value}"
          @click="updateValue(item.value)">
      {{ item.label }}
    </span>
  </div>
</template>

<script>
export default {
  name: "index",

  props: {
    radioList: Array,
    value: String
  },

  methods: {

    // 改变value的值
    updateValue(val){
      this.$emit('input',val)
    }
  }
}
</script>

<style scoped>
/*按钮组的布局*/
.radio-btn {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: wrap;
}
/*按钮的文字大小样式*/
.radio-span{
  min-width: 6em;
  text-align: center;
  border-radius: 16px;
  margin: 0.5em 1em;
  border: #DCDFE6 solid 1px;
  padding: 0.5em;
  background-color: #FAFAFA;
}

/*按钮鼠标悬停样式*/
.radio-span:hover{
  cursor: pointer;
  color: #F56C6C;
  background-color: #FEF0F0;
  border-color: red;
}

/*按钮选中样式*/
.radio-span-active{
  cursor: pointer;
  color: white;
  background-color: #e84949;
}
/*按钮选中之后鼠标悬停样式,不写的话就被上面那个按钮悬停样式覆盖了*/
.radio-span-active:hover{
  cursor: pointer;
  color: white;
  background-color: #e84949;
}
</style>

我们使用这个组件的时候就可以这样使用了

<template>
<div class="ml-4em mt-4em">
  <h3>单选按钮</h3>

  <radio-button :radio-list="radioList" v-model="radioValue"></radio-button>

  <p>选中的按钮value为<span class="radio-value ml-1em">{{radioValue}}</span></p>
</div>
</template>

<script>
import RadioButton from '@/components/RadioButton'
export default {
  name: "index",
  components: {
    RadioButton
  },
  data(){
    return {
      radioValue: 'sm',
      radioList: [
        {
          label: '小号',
          value: 'sm'
        },
        {
          label: '中号',
          value: 'md'
        },
        {
          label: '大号',
          value: 'lg'
        }
      ]
    }
  }

}
</script>

<style scoped>
.radio-value {
  color: red;
  font-size: 1.2em;
}
</style>

页面效果截图如下。
请添加图片描述

相关代码放在这里:https://gitee.com/siumu/blog_code.git
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值