VUE渲染後元素丟失(或元件丟失)的解決方案
阿新 • • 發佈:2021-02-11
VUE渲染後元素丟失(或元件丟失)的解決方案
背景
最近需要整合各種微服務元件,但大多數微服務元件沒有介面或介面不符合需求,所以決定為微服務元件介面化或對已有介面進行更改,以達到統一的介面風格,為整體微服務系統提供一整套視覺化服務
考慮因素
- 開發上手難度
- 如果需要進行前後端分離,遷移改造難度
- 與當前公司所用前端框架是否適配
- 是否有可以進行較好的除錯(熱更新、近實時更新)
解決方案
- 由於多數微服務元件是構建於 SpringBoot 之上,所有決定將介面放置於元件內部,當微服務元件啟動後可直接進行訪問
- 根據公司採用的前端框架是 vue(使用 nodeJs 單獨啟動的前端),鑑於未來遷移改造難度,介面也決定採用 vue 方案,只不過採用的是 html 檔案引入 js 的方式
- 通過直接修改Idea編譯後的target目錄下的靜態檔案,可實現頁面和樣式的近實時更新
示例專案
Gitee開源專案地址 https://gitee.com/refiner/refine-boot-vue
採用 vue 版本:v2.6.10
特別說明:專案採用的是以靜態檔案的方式引入VUE,即使用 <script type="text/javascript" th:src="@{/js/vue.min.js}"></script>
遇到的問題
問題描述:如下圖所示,圖片上的操作列可能不顯示或表格後的分頁元件不顯示,通過F12檢視原始碼,發現程式碼丟失
程式碼示例(官網上的程式碼)
<template> <el-table :data="tableData" border style="width: 100%"> <el-table-column fixed prop="date" label="日期" width="150"> </el-table-column> ... <el-table-column fixed="right" label="操作" width="100"> <template slot-scope="scope"> <el-button @click="handleClick(scope.row)" type="text" size="small">檢視</el-button> <el-button type="text" size="small">編輯</el-button> </template> </el-table-column> </el-table> </template>
問題原因
Vue頁面使用 <template>
標籤來巢狀到 <router-view>
中從而展示頁面,但是引用js的工程中使用如上程式碼方式會造成 <template>
巢狀,即 檢視 和 編輯 操作也使用了 <template>
來渲染,所以造成元素編譯後丟失
解決方案
- 已確定是因為
<template>
標籤巢狀而導致渲染後元素丟失,所以只要 檢視 和 編輯 操作改用不使用<template>
來包括即可,經過試驗,發現可以使用<slot>
標籤替代<template>
,替換後渲染,不會造成元素編譯後丟失
解決後代碼示例
<template>
<el-table
:data="tableData"
border
style="width: 100%">
<el-table-column
fixed
prop="date"
label="日期"
width="150">
</el-table-column>
...
<el-table-column
fixed="right"
label="操作"
width="100">
<slot slot-scope="scope">
<el-button @click="handleClick(scope.row)" type="text" size="small">檢視</el-button>
<el-button type="text" size="small">編輯</el-button>
</slot>
</el-table-column>
</el-table>
</template>