之前需要對 el-button 做二次封裝,所以就用到 vue 的 $attrs 和 $listeners 屬性,這兩個屬性在這不細說,可以在這里 查看詳情。
二次封裝代碼(limit-button)
<template>
<el-button
v-show="validButton"
v-bind="$attrs"
v-on="$listeners"
>
<slot></slot>
</el-button>
</template>
<script>
import { mapGetters } from 'vuex';
import env from '@/config/env';
export default {
props: {
// 按鈕唯一標識
buttonId: {
type: String,
required: true,
},
},
computed: {
...mapGetters(['getUserBtns']),
validButton: function() {
return env.debug ? true : this.getUserBtns[this.buttonId];
},
},
};
</script>
這樣封裝的好處就是不需要將上層每個屬性都寫一次 prop 定義,對 listeners 也不需要做一層中轉 emit 。
發現問題
在某個頁面,點擊經過封裝的 limit-button 會使頁面進行刷新
起初以為是點擊事件的冒泡產生的,就把上層引用的 @click 去掉:
<limit-button type="warning" size="small" buttonId="2345434fg" > 點擊 </limit-button>
發現還是一樣會產生刷新的事件。
思考可能是 $listeners 的問題,在 mounted 中打印也只有 @click 事件,就算去掉 $listeners 也不管用。 后來在瀏覽器對dom結構的查看,發現 limit-button 編譯后變成:
可以看到編譯后的 type 變成了 warning ,查 element 的源碼可發現
<button class="el-button" @click="handleClick" :disabled="buttonDisabled || loading" :autofocus="autofocus" :type="nativeType" ... > <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>
可發現是 $attrs 覆蓋了 el-button 的nativeType
問題簡化重現
<el-form ref="form" :model="form" label-width="80px"> <el-form-item> <button type="primary">點擊會刷新</button> <button type="button" @click="onSubmit">點擊不會刷新</button> </el-form-item> </el-form>
重現鏈接
解決方法
將 type 分出來 props ,然后再通過 prop 引用
<template>
<el-button
:type="type"
v-show="validButton"
v-bind="$attrs"
v-on="$listeners"
>
<slot></slot>
</el-button>
</template>
<script>
import { mapGetters } from 'vuex';
import env from '@/config/env';
export default {
props: {
// 按鈕唯一標識
buttonId: {
type: String,
required: true,
},
type: {
type: String,
}
},
computed: {
...mapGetters(['getUserBtns']),
validButton: function() {
return env.debug ? true : this.getUserBtns[this.buttonId];
},
},
};
</script>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。