二次封裝element-ui table,操作列手動傳入按鈕


我們在使用element-ui時,必定會用到表格這個組件,雖然element組件已經為我們封裝很好了。但是我們在實際開發中會根據我們的業務在element-ui的基礎上再次封裝,比如表格最后一列會經常有操作這一列,對應着不同的按鈕,像編輯按鈕、查看按鈕、刪除按鈕等,有些表格的結構類似,顯示數據和操作,差別只是在於后邊操作按鈕不相同,此時,封裝一個業務組件,手動傳入需要的按鈕,這樣,在遇到類似的情況就可以直接使用該業務組件。具體 實現思路如下:

basicTable.vue組件

        <el-table
            :data="tableData"
            stripe
            @selection-change="handleSelectionChange"
            style="width: 100%;">
            <el-table-column
                v-if="isCheckbox"
                type="selection"
                
                width="50">
            </el-table-column>
            <el-table-column
                v-for="column in tableHeader"
                :key="column.label"
                :label="column.label"
                :width="column.width">
                <template slot-scope="scope">
                    <span>{{ scope.row[column.prop] }}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                v-if="isOperate">
                <template slot-scope="scope">
                    <slot :row='scope.row' :index='scope.$index'></slot>
                </template>
            </el-table-column>
            <div slot="empty">
                <span>暫無數據</span>
            </div>
        </el-table>    

要想實現想要的功能,最重要的是slot那段代碼,我使用的是slot插槽,用來接收父組件傳進來的數據,這樣一來,我們在父組件調用basicTable組件時,傳入需要顯示的按鈕,這樣按鈕就會在slot插槽的位置顯示出來。

在父組件中使用BasicTable.vue

        <BasicTable :isOperate='true' :tableHeader="tableHeader" :isCheckbox='true' @isSelectCheck="isSelectCheck">
            <template slot-scope="data">
                <el-button
                v-if="false"
                size="mini"
                type="primary"
                @click="attention(data.index, data.row)">互關</el-button>
                <el-button
                v-else
                size="mini"
                type="danger"
                @click="cancelAttention(data.index, data.row)">取關</el-button>
            </template>
        </BasicTable>    

在父組件中使用基礎組件時,在basictable標簽中傳入要使用的按鈕。最最容易入坑的是在綁定事件的時候,我在互關的按鈕綁定點擊事件attention,在傳入參數的時候,怎么讓按鈕點擊的時候拿到當前列和表格數據,我們在直接使用element提供的table的時候,可以直接綁定點擊事件,就像這樣

<el-table-column label="操作">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">編輯</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">刪除</el-button>
      </template>
</el-table-column>

但是我哦們把template里邊的內容換成了<slot></slot>

我們可以通過slot將scope傳到父組件,在這里最最需要注意的是需要什么數據就傳什么數據,就像在basictable.vue代碼中那樣 ,雖然我們可以通過scope拿到表格的相關數據,但是不能直接通過slot直接將scope傳出去,至於為什么,就不知道了。為了和之前的scope區別開,我在父組件中接收的時候起了個名字叫data,其實叫scope叫什么都無所謂,這樣,就能拿到想要的數據了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM