使用 vite2.0+vue3+element Plus+vue-router 搭建一个简单的项目

3,946 阅读2分钟

最近一直在关注vue3,之前尝试过用element Plus 和 vue3 ,构建工具是vite1.+,但是搭建过程中发现 element Plus 的国际化配置成中文后,vite 打包会报错,不能正常发布,前段时发现elementPlus 的官网说已经解决了,所以今天又来尝试一下。废话不多说,直接上过程代码及步骤: 首先构建工具有 webpack、vue-cli、vite,我用的是 vite, 构建vue3 项目

# npm 6.x
npm init @vitejs/app vue3_elementplus --template vue

cd vue3_elementplus
npm install
npm run dev

这样就简单的构建了一个vue3 的项目,还有其他构建方式可自行查看官方文档

引入 element Plus

npm install element-plus -S
```js
引入好后就开始配置 element Plus 了,可按照官网来配置,我这里写一下我自己的配置,我用的是按需加载的,引用一个库:unplugin-vue-components
```js
npm install unplugin-vue-components -D

在 vite.config.js 文件中引用

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
  plugins: [
    vue(),
    Components({
      resolvers: [ElementPlusResolver()],
      dts: true,
      include: [/\.vue$/, /\.vue\?vue/, /\.md$/]
    })
  ],
  ......
})

在 main.js 文件中需要引入样式文件

import 'element-plus/dist/index.css'

这样可以在任何组件中使用了,如下:

<template>
    <el-button type="primary">按钮</el-button>
</template>

element Plus 有些模块需要手动在组件中引用,才能正常使用,例如:Message

<script setup>
    import { ElMessage } from "element-plus";
    
    function msg() {
        ElMessage({
            showClose: true,
            type: "success",
            message: "成功提示!"
        });
    }
</script>

<template>
    <el-button @click="msg">提示</el-button>
</template>
<style>....</style>

接下来就是全家桶之一的路由咯:vue-router,现在版本为 @4 的才支持 vue3,所以引入方式如下:

npm install vue-router@4 -S

引入后需要配置一下,在 src 目录下新建一个 router 目录,再里面新建一个 index.js 文件

import { createRouter, createWebHashHistory } from "vue-router";

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: '/',
            component: () => import('../views/index.vue') // 这是路由的籁加载,也可以其他方式
        }
    ]
})

export default router;

配置完后在 main.js 文件中引用就好了

import { createApp } from 'vue'
import App from './App.vue'
import routers from './router/index'

import 'element-plus/dist/index.css'

createApp(App)
.use(routers)
.mount('#app')

最后修改一下 APP.vue 文件

<template>
    <router-view></router-view>
</template>
......

这样就已经大功告成了,简单的项目框架就已成型。

初次编写,如有错误地方,欢迎留言来喷。