建網(wǎng)站的公司大全開創(chuàng)集團與百度
因為我們要根據(jù)路由配置對應(yīng)的圖標(biāo),也要為了后續(xù)方便更改。因此我們將所有的圖標(biāo)注冊為全局組件。(使用之前將分頁器以及矢量圖注冊全局組件的自定義插件)(所有圖標(biāo)全局注冊的方法element-plus文檔中已給出)
全局注冊elementPlus
圖標(biāo)
經(jīng)過上面的步驟,就可以把elementPlus
自帶的icon
圖標(biāo)全局注冊了。
路由使用elementPlus
圖標(biāo)
給路由元信息添加屬性:icon
以layout
和其子組件為例:首先在element-puls
找到你要使用的圖標(biāo)的名字。將它添加到路由元信息的icon
屬性上
{//登錄成功以后展示數(shù)據(jù)的路由path: '/',component: () => import('@/layout/index.vue'),name: 'layout',meta: {title: 'layout',hidden: false,icon: 'Avatar',//elementPlus中的圖標(biāo)},children: [{path: '/home',component: () => import('@/views/home/index.vue'),meta: {title: '首頁',hidden: false,icon: 'HomeFilled',//elementPlus中的圖標(biāo)},},],
},
外部引入的svg
圖標(biāo)——vite.config.js
中批量引入
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
export default defineConfig(({command,mode})=>{const env = loadEnv(mode,process.cwd())return {plugins:[vue(),AutoImport({resolvers: [ElementPlusResolver(),IconsResolver({prefix: 'Icon',}),],}),Components({resolvers: [ElementPlusResolver(),IconsResolver({enabledCollections: ['ep'],}),],}),Icons({autoInstall: true,}),createSvgIconsPlugin({// Specify the icon folder to be cachediconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],// Specify symbolId formatsymbolId: 'icon-[dir]-[name]',}),]}
})
然后svg
圖標(biāo)的使用,例如全屏
圖標(biāo):
<el-button icon="FullScreen" circle @click="fullScreen" />
順道寫下全屏
功能的實現(xiàn):
<script lang="ts" setup>
import {reactive,ref} from 'vue';
//全屏功能
const fullScreen = ()=>{//用來判斷是不是全屏,返回布爾值const full = document.fullscreenElement//有兼容問題if(full){document.exitFullscreen();}else{document.documentElement.requestFullscreen();}
}
</script>
components
中的組件全局批量注冊——避免使用時多次引入
步驟一:在components
文件夾中新建index.ts
文件
步驟二:在index.ts
文件中引入各個組件
import SvgIcon from './SvgIcon/index.vue'
import Category from '@/components/Category/index.vue'
步驟三:使用vue
中的App
和Component
import type { App, Component } from 'vue'
const allGlobalComponent: Component = { SvgIcon, Category }
步驟四:使用install
方法來處理
export default {install(app: App) {Object.keys(allGlobalComponent).forEach((key: string) => {// 注冊為全局組件app.component(key, allGlobalComponent[key])})},
}
結(jié)合文章中第一步的全局引入elementPlus
圖標(biāo),也可以放在此文件中:
完整代碼如下:
import SvgIcon from './SvgIcon/index.vue'
import Category from '@/components/Category/index.vue'
import type { App, Component } from 'vue'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
const allGlobalComponent: Component = { SvgIcon, Category }
export default {install(app: App) {Object.keys(allGlobalComponent).forEach((key: string) => {// 注冊為全局組件app.component(key, allGlobalComponent[key])})// 將 element-plus 的圖標(biāo)注冊為全局組件for (const [key, component] of Object.entries(ElementPlusIconsVue)) {app.component(key, component)}},
}
main.ts
中引入components
import globalComponent from './components/index'
const app = createApp(App)
app.use(globalComponent)