欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解關(guān)于element el-button使用$attrs的一個(gè)注意要點(diǎn)

 更新時(shí)間:2018年11月09日 10:13:18   作者:天驅(qū)  
這篇文章主要介紹了詳解關(guān)于element el-button使用$attrs的一個(gè)注意要點(diǎn),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

之前需要對(duì) el-button 做二次封裝,所以就用到 vue$attrs$listeners 屬性,這兩個(gè)屬性在這不細(xì)說(shuō),可以在這里 查看詳情。

二次封裝代碼(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: {
  // 按鈕唯一標(biāo)識(shí)
  buttonId: {
   type: String,
   required: true,
  },
 },

 computed: {
  ...mapGetters(['getUserBtns']),
  validButton: function() {
   return env.debug ? true : this.getUserBtns[this.buttonId];
  },
 },
};
</script>

這樣封裝的好處就是不需要將上層每個(gè)屬性都寫一次 prop 定義,對(duì) listeners 也不需要做一層中轉(zhuǎn) emit 。

發(fā)現(xiàn)問(wèn)題

在某個(gè)頁(yè)面,點(diǎn)擊經(jīng)過(guò)封裝的 limit-button 會(huì)使頁(yè)面進(jìn)行刷新

起初以為是點(diǎn)擊事件的冒泡產(chǎn)生的,就把上層引用的 @click 去掉:

<limit-button
  type="warning"
  size="small"
  buttonId="2345434fg"
>
點(diǎn)擊
</limit-button>

發(fā)現(xiàn)還是一樣會(huì)產(chǎn)生刷新的事件。

思考可能是 $listeners 的問(wèn)題,在 mounted 中打印也只有 @click 事件,就算去掉 $listeners 也不管用。 后來(lái)在瀏覽器對(duì)dom結(jié)構(gòu)的查看,發(fā)現(xiàn) limit-button 編譯后變成:

 

可以看到編譯后的 type 變成了 warning ,查 element 的源碼可發(fā)現(xiàn)

<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>

可發(fā)現(xiàn)是 $attrs 覆蓋了 el-button 的nativeType

問(wèn)題簡(jiǎn)化重現(xiàn)

<el-form ref="form" :model="form" label-width="80px">
 <el-form-item>
  <button type="primary">點(diǎn)擊會(huì)刷新</button>
  <button type="button" @click="onSubmit">點(diǎn)擊不會(huì)刷新</button>
 </el-form-item>
</el-form>

重現(xiàn)鏈接

解決方法

type 分出來(lái) props ,然后再通過(guò) 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: {
  // 按鈕唯一標(biāo)識(shí)
  buttonId: {
   type: String,
   required: true,
  },
  type: {
    type: String,
  }
 },

 computed: {
  ...mapGetters(['getUserBtns']),
  validButton: function() {
   return env.debug ? true : this.getUserBtns[this.buttonId];
  },
 },
};
</script>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論