vue中處理多類型button(render方法)

文章借鑑於掘金,在這裏種草 https://juejin.im/post/5e475829f265da57444ab10f

通過v-if來進行多種類型的判斷,會使代碼十分複雜,我們需要去封裝一個button組件

<template>
  <div>
    <h1>I am Home</h1>
    <!-- 假設按鈕有多種類型,通過value來顯示不同類型 -->
    <div v-if='value === 1'>
      <button>button1</button>
    </div>
    <div v-else-if='value === 2'>
      <button>button2</button>
    </div>
    <div v-else>
      <button>button3</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Home',
  data(){
    return{
        value:1
    }
  },
  methods:{
  }
}
</script>

<style scoped lang="less">
</style>

創建一個button.vue文件 寫法如下

 
<script>
export default {
    props:{
        type:{
            type:String,
            default:'normal'
        },
        text:{
            type:String,
            default:'button'
        }
    },
    render(h){
        /*
            h 類似於 createElement, 接受2個參數
            1 - 元素
            2 - 選項
         */
        return h('button',{
            // 相當於 v-bind:class
            class:{
                btn:true,
                'btn-success':this.type === 'success',
                'btn-danger':this.type === 'danger',
                'btn-warning':this.type === 'warning',
                'btn-normal':this.type === 'normal',
            },
            domProps:{
                innerText: this.text || '默認'
            },
            on:{
                click:this.handleClick
            }
        })
    },
    methods:{
        handleClick(){
            this.$emit('myClick')
        }
    }
}
</script>

<style scoped>
.btn{
    width: 100px;
    height:40px;
    line-height:40px;
    border:0px;
    border-radius:5px;
    color:#ffff;
}
.btn-success{
    background:#2ecc71;
}
.btn-danger{
    background:#e74c3c;
}
.btn-warning{
    background:#f39c12;
}
.btn-normal{
    background:#bdc3c7;
}
</style>

// 引入



<template>
  <div>
    <h1>I am Home</h1>
    <!-- 按鈕根據value顯示不同類型的button -->
    <Button type='success' text='button1' @myClick='...'></Button>
  </div>
</template>

<script>
import Button from './button.vue'
export default {
  name: 'Home',
  data(){
    return{
        value:1
    }
  },
  components:{
      Button
  },
  methods:{
  }
}
</script>

<style scoped lang="less">
</style>

上面這種寫法,根據value來顯示不同類型的button,我們只需要通過value去修改type,text等,就可以實現這一目的,而不需要去創建多個,通過v-if去判斷

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章