本组件二次封装iview的Button,可以在全局安装了Iview的项目或者局部引入了Button的页面中自由使用。
目录
效果展示
 
从上到下分别是:选中状态按钮、取消选中状态按钮
功能描述
- 按钮名和按钮状态均可由父组件传参到子组件
 - 点击选中,点击取消
 - 可组合使用,实现类似按钮样式的tab,将所有tab的状态和名字保存在一个attrs数组里面
 
结构代码
<template>
  <div class="c-btn">
    <Button v-if="checked" type="primary" @click="check_btn">{
  {
      checked_name ? checked_name : name
    }}</Button>
    <Button v-else type="primary" ghost @click="check_btn">{
  {
      unchecked_name ? unchecked_name : name
    }}</Button>
  </div>
</template>
  - checked_name:父组件没有命名时使用默认名字
 - checked:子组件的按钮选中状态由父组件决定
 
逻辑代码
  data () {
   
    return {
   
      checked: this.check_state
    }
  },
  props: {
   
    name: {
   
      type: String,
      default () {
   
        return }
    },
    checked_name: {
   
      type: String,
      default () {
   
        return ''
      }
    },
    unchecked_name: {
   
      type: String,
      default () {
   
        return ''
      }
    },
    check_state: {
   
      type: Boolean,
      default () {
   
        return false
      }
    }
  },
  methods: {
   
    check_btn () {
   
      this.checked = !this.checked
      this.$emit('click', this.checked, this.name)
    }
  },
  watch: {
   
    check_state (n, o) {
   
      if (n !== o) {
   
        this.checked = n
      }
    }
  }
  - check_btn :状态改变回传到父组件,由父组件来决定子组件的状态
 - check_state :监听父组件传递的按钮选中状态,同步变化
 
组件应用
<cBtn
    name=
    :check_state="attrs[0].checked"
    @click="attr_handle"
/>
import cBtn from '@/components/c-btn'
components: {
   
    cBtn 
}
data () {
   
    return {
   
        attrs: attrBox.attrs
    }
}
  - import引入——>组件注册——>使用
 - 父——>子传参:name按钮名字、check_state选中状态
 
事件钩子
// 属性处理
    attr_handle (checked, attr_name) {
   
      this.attrs.forEach((a) => {
   
        if (a.name !== attr_name && a.checked && checked) {
   
          a.checked = false
        } else if (a.name === attr_name) {
   
          a.checked = checked
        }
      })
      if (checked) this.cur_attr = attr_name
    }
  - attr_handle:属性处理
 
github
完整代码:点击这里

京公网安备 11010502036488号