项目结构
vue3-ts-cms
├─ .browserslistrc
├─ .editorconfig
├─ .env.development
├─ .env.production
├─ .env.test
├─ .eslintrc.js
├─ .gitignore
├─ .prettierignore
├─ .prettierrc
├─ babel.config.js
├─ package-lock.json
├─ package.json
├─ public
│ ├─ favicon.ico
│ └─ index.html
├─ README.md
├─ src
│ ├─ App.vue
│ ├─ assets
│ │ └─ css
│ │ ├─ base.less
│ │ ├─ index.less
│ ├─ components
│ ├─ global
│ │ ├─ index.ts
│ │ └─ register-element.ts
│ ├─ main.ts
│ ├─ router
│ │ └─ index.ts
│ ├─ shims-vue.d.ts
│ ├─ store
│ │ └─ index.ts
│ └─ views
│ ├─ login
│ │ └─ login.vue
│ └─ main
│ └─ main.vue
├─ tsconfig.json
└─ vue.config.js
element-plus集成
Element Plus,一套为开发者、设计师和产品经理准备的基于 Vue 3.0 的桌面端组件库。正是element-ui针对于vue3开发的一个UI组件库。
安装element-plus
npm install element-plus --save
全局引入
全局引入就是在入口文件main.ts
中引入 element-plus,代表所有的组件和插件都会被自动注册。
import ElementPlus from 'element-plus'
import 'element-plus/lib/theme-chalk/index.css'
createApp(App).use(ElementPlus).mount('#app')
按需引入
按需引入也就是在开发中用到某个组件对某个组件进行引入。
在根目录下创建global文件夹,在此文件夹下创建 index.ts、register-element.ts 文件。
按需引入组件
register-element.ts
import { App } from 'vue'
import 'element-plus/lib/theme-chalk/base.css'
import { ElButton, ElInput } from 'element-plus'
const components = [ElButton, ElInput]
// 按需注册组件
export default function (app: App): void {
for (const c of components) {
app.component(c.name, c)
}
}
index.ts
import { App } from 'vue'
import registerElement from './register-element'
export function globalRegister(app: App): void {
// 注册element组件
registerElement(app)
}
main.ts
import { createApp } from 'vue'
import App from './App.vue'
import { globalRegister} from './global'
const app = createApp(App)
app.use(globalRegister)
app.mount('#app')
按需引入样式
安装插件:babel
npm install babel-plugin-import -D
配置 babel.config.js文件,根据引入的组件名称,自动引入对应的样式文件
babel.config.js
module.exports = {
plugins: [
[
'import',
{
libraryName: 'element-plus',
customStyleName: (name) => {
return `element-plus/lib/theme-chalk/${name}.css`
}
}
]
],
presets: ['@vue/cli-plugin-babel/preset']
}
按照上述方式,运行时提示下图错误。应该是element-plus版本更新,文件路径更换导致异常。
可以参考这里
App.vue
<template>
<div>
<el-button>默认按钮</el-button>
<el-button type="primary">主要按钮</el-button>
<el-button type="success">成功按钮</el-button>
<el-button type="info">信息按钮</el-button>
<el-button type="warning">警告按钮</el-button>
<el-button type="danger">危险按钮</el-button>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
name: 'App',
components: {}
})
</script>
<style lang="less">
</style>