一個src文件夾和一個index.js,src文件夾放組件,index.js註冊組件並導出
分析從三個方面着手:DOM結構,數據屬性,事件
1.DOM結構:
<button></button>
2.數據屬性
1)props獲取
2)引用computed的屬性
3.事件
這裏涉及到父子組件通信,子組件向父組件發消息可以用emit實現,父組件監聽即可,一般情況下父組件監聽的事件名都是自定義的,這裏特殊了點,父組件直接監聽了“click”事件,誰讓button通常就一個點擊事件呢
學習點:
1)樣式綁定
:class="[
type ? 'el-button--' + type : '',
buttonSize ? 'el-button--' + buttonSize : '',
{
'is-disabled': buttonDisabled,
'is-loading': loading,
'is-plain': plain,
'is-round': round,
'is-circle': circle
}
]"
class的綁定
綁定的class做了歸類,boolean類型的歸爲了一類,放到對象中,我們是不是也可以這樣寫,讓代碼更整齊呢
https://cn.vuejs.org/v2/guide/class-and-style.html#%E6%95%B0%E7%BB%84%E8%AF%AD%E6%B3%95
2)插槽
插槽就是子組件中的提供給父組件使用的一個佔位符,用 表示,父組件可以在這個佔位符中填充任何模板代碼,如 HTML、組件等,填充的內容會替換子組件的標籤。
<span v-if="$slots.default"><slot></slot></span>
https://www.cnblogs.com/mandy-dyf/p/11528505.html
https://cn.vuejs.org/v2/api/#vm-slots
附源碼
<template>
<button
class="el-button"
@click="handleClick"
:disabled="buttonDisabled || loading"
:autofocus="autofocus"
:type="nativeType"
:class="[
type ? 'el-button--' + type : '',
buttonSize ? 'el-button--' + buttonSize : '',
{
'is-disabled': buttonDisabled,
'is-loading': loading,
'is-plain': plain,
'is-round': round,
'is-circle': circle
}
]"
>
<i class="el-icon-loading" v-if="loading"></i>
<i :class="icon" v-if="icon && !loading"></i>
<span v-if="$slots.default"><slot></slot></span>
</button>
</template>
<script>
export default {
name: 'ElButton',
inject: {
elForm: {
default: ''
},
elFormItem: {
default: ''
}
},
props: {
type: {
type: String,
default: 'default'
},//類型 string primary / success / warning / danger / info / text
size: String, //尺寸 string medium / small / mini
icon: {
type: String,
default: ''
},
nativeType: {
type: String,
default: 'button'
},
loading: Boolean,
disabled: Boolean,
plain: Boolean,
autofocus: Boolean,
round: Boolean,
circle: Boolean
},
computed: {
_elFormItemSize() {
return (this.elFormItem || {}).elFormItemSize;
},
buttonSize() {
return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
},
buttonDisabled() {
return this.disabled || (this.elForm || {}).disabled;
}
},
methods: {
handleClick(evt) {
this.$emit('click', evt);
}
}
};
</script>