1. 程式人生 > 其它 >element-ui按需引入遇到的一些問題

element-ui按需引入遇到的一些問題

element-ui按需引入踩的坑(Vue)

一、按需引入的步驟

1. 下載

npm i element-ui -S

2. 配置bable.config.js檔案

{
/* "presets" 使用腳手架中自帶的配置即可" */
"presets": [["es2015", { "modules": false }]],
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}

3. 在main.js中匯入需要的元件

例:引入Button元件

import { Button } from 'element-ui';
Vue.use(Button);

坑1:想要使用某個元件,有可能需要引入多個元件

import { Carousel } from 'element-ui';
Vue.use(Carousel);
Vue.use(CarouselItem);

坑2:使用Vue.use()可能會出現bug,比如使用MessageBox元件時,使用Vue.use()會導致頁面一重新整理就彈框,此時應該用Vue.component()替代

import { MessageBox } from 'element-ui';
Vue.component(MessageBox.name, MessageBox)

二、MessageBox的簡單使用

1. 建議使用前在main.js
中先放入Vue的原型物件(如果是全域性引入則已經自動完成這一步)

import { MessageBox } from 'element-ui';
Vue.component(MessageBox.name, MessageBox);
/* 這樣就可以使用跟官網案例一樣的變數名 */
Vue.prototype.$msgbox = MessageBox;
Vue.prototype.$alert = MessageBox.alert;
Vue.prototype.$confirm = MessageBox.confirm;
Vue.prototype.$prompt = MessageBox.prompt;

2. 官網案例 ”訊息提示“

open() {
  this.$alert('這是一段內容', '標題名稱', {
    confirmButtonText: '確定',
    /* 關閉彈窗後的回撥,彈出使用者選擇結果(confirm | cancel等)的提示資訊 */
    callback: action => {
      /* this.$message用的另一個元件Message,需要匯入才能使用 */
      this.$message({
        type: 'info',
        message: `action: ${ action }`
       });
     }
  });
}        

3. 官網案例 "自定義"

(我程式碼中的)坑:點選觸發事件的按鈕後,彈框中的確認按鈕不能自動獲取焦點,焦點一直停留在觸發事件的按鈕上,導致按回車鍵時,效果不是關閉彈窗,而是不停的觸發事件以致於一按回車就彈出一個框。

解決思路兩個:1. 讓觸發事件的按鈕禁用enter 2. 彈窗後更換焦點到框中確認按鈕上

讓觸發事件的按鈕禁用enter

<button @*click*="register" *onkeydown*="if(event.keyCode==13){return false;}">點選註冊</button>

彈窗後更換焦點到框中確認按鈕上,嘗試在beforeClose回撥中獲取該按鈕,再.focus,行不通,估計涉及到vue中dom操作被覆蓋的問題。所以confirmButtonClass: 'mybtn'自定義了類名,然後獲取該確認按鈕物件,所以考慮放在Vue.nextTick()回撥函式中的執行,即當資料更新了,在dom中渲染後,自動執行該函式中的.focus。因此想到用setTimeout來執行,因為是非同步,會等主程式執行完畢後執行,故在這個全是同步操作的函式register中,會將所有主程式中的執行完了再.focus,這樣有可能會避免操作被覆蓋的情況,嘗試後確實可以完成需求。

	const h = this.$createElement;
        this.$msgbox({
          title: '提示資訊',
          message:  h('p', {style: 'font-size: 16px;'},'驗證碼錯誤!'),
          confirmButtonText: '確定',
          closeOnClickModal: false,
          confirmButtonClass: 'mybtn',
          beforeClose: (action, instance, done) => {
            /* 下面註釋的這條程式碼讓確認按鈕獲取焦點 */
            // instance.$refs['confirm'].$el.focus;
            if (action === 'confirm') {
              // 註釋掉的程式碼用於禁用enter確認(還沒有發現是焦點的問題前,以為是enter導致的多次彈窗)
              /* instance.$refs['confirm'].$el.onclick = function(e) {
                 e = e || window.event;
                 // 如果不是鍵盤觸發的事件(這裡禁止enter進行確認)
                 if (e.detail !== 0) {
                   done();
                 }
                }(); */
              console.log('已經確認');
              done();
            } else {
              done();
            }
          }
        })
        setTimeout(() => {
          document.getElementsByClassName('mybtn')[0].focus();
        });