0、寫在前面
vue3正式版發(fā)布一年多了,elementplus也跟進(jìn)了vue3版本,真是廣大開發(fā)者的福音,今天就用vue3+vite+elementplus搭建一個開發(fā)框架模板。這里全程使用 yarn 命令,不太熟悉的童鞋請參考文章 yarn和npm常用開發(fā)命令對比。
由于這篇文章開發(fā)框架功能和思路沿用的之前文章,并且之前vue2+elementUI的教程從起步到權(quán)限控制說的比較詳細(xì),所以這里著重說一下vue3和vue2搭建形式和方法運(yùn)用不一樣的地方,即 vue-router路由 部分和 element-plus組件 的新式使用方式,剩下部分童鞋們可以自己動手豐衣足食,哈哈。。另外vue3的語法用法請直接參考官網(wǎng) Vue.js (vuejs.org)
閑話不多說,下面正式開始。
1、新建項目
● 新建項目 vue3-elementplus
yarn create vite vue3-elementplus --template vue

● 啟動
yarn dev
2、路由 vue-router
這里可以新打開一個terminal窗口
● 安裝
yarn add vue-router -S
● 編寫頁面,新建 src>views>Index.vue
<template>
<h1>首頁</h1>
<p>Index</p>
</template>
● 新建 src>views>List.vue
<template>
<h1>列表</h1>
<p>List</p>
</template>
● 新建 src>views>404.vue
<template>
<p>404</p>
</template>
● 路由文件,新建 src>router>index.js
import { createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: "/",
redirect: '/index'
},
{
path: "/index",
component: () => import('../views/Index.vue')
},
{
path: "/list",
component: () => import('../views/List.vue')
},
{
path: "/404",
component: () => import('../views/404.vue')
},
{
path: "/:pathMatch(.*)*",
redirect: '/404'
}
]
})
export default router
● 修改 App.vue文件
<template>
<router-view />
</template>
● main.js 中引入路由文件
import { createApp } from 'vue'
import App from './App.vue'
+ import router from './router/index'
- createApp(App).mount('#app')
+ const app = createApp(App).use(router)
+ app.mount('#app')
如果剛剛是打開新的terminal安裝的vue-router,現(xiàn)在直接在地址欄中訪問 http://localhost:3000/#/ 和 http://localhost:3000/#/list 即可,也不用重啟了,快活呀。。這就是vite Home | Vite中文網(wǎng) (vitejs.cn)
2、安裝 element-plus
這里我們使用官網(wǎng)推薦的自動導(dǎo)入的方式
yarn add element-plus
yarn add unplugin-vue-components unplugin-auto-import -D
修改vite配置文件vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
+ import AutoImport from 'unplugin-auto-import/vite'
+ import Components from 'unplugin-vue-components/vite'
+ import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
// https://vitejs.dev/config/
export default defineConfig({
- plugins: [ vue()]
+ plugins: [
+ vue(),
+ AutoImport({
+ resolvers: [ElementPlusResolver()],
+ }),
+ Components({
+ resolvers: [ElementPlusResolver()],
+ })
+ ]
})
使用element-plus 組件,修改文件 src/views/Index.vue
<template>
<h1>首頁</h1>
<p>Index</p>
+ <div>
+ <el-button type="primary" icon="edit">Primary</el-button>
+ <el-button type="success">Success</el-button>
+ <el-button type="info">Info</el-button>
+ <el-button type="warning">Warning</el-button>
+ <el-button type="danger">Danger</el-button>
+ <el-button>中文</el-button>
+ </div>
</template>
這里全部保存直接生效,真是太方便了!截圖如下:
