Steps to build the vite+vue3+element-plus project

Steps to build the vite+vue3+element-plus project

Use vite to build a vue3 project

You can quickly build a Vue project using Vite by running the following command in your terminal.

$ npm init vite-app <project-name>
$ cd <project-name>
$ npm install
$ npm run dev

Introducing Element Plus

Install Element Plus:

npm install element-plus --save

Element Plus is fully introduced in main.js:

import { createApp } from 'vue'
import ElementPlus from 'element-plus';
import 'element-plus/lib/theme-chalk/index.css';
import App from './App.vue';

const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')

Importing SCSS

Run the command to install sass, npm i sass -D, and then add lang="scss" to the style tag of the vue file. These are the same as before vue2.

npm i sass -D

Import eslint

Install eslint

npm i eslint -D

Use eslint to initialize this project

npx eslint --init

Follow the prompts to set up, this is the setting I chose

Import vue-router

Install Vue Router 4

npm install vue-router@4

Create a new router folder in the src directory, and create index.js under router for routing configuration

import * as VueRouter from 'vue-router'

const routes = [
  {
    path: '/',
    component: () => import('../page/Home.vue')
  }, {
    path: '/login',
    component: () => import('../page/Login.vue')
  }
]

export default VueRouter.createRouter({
  history: VueRouter.createWebHashHistory(),
  routes
})

Use this middleware in main.js

import router from './router'
//...
app.use(router)

Import vuex

Install vuex

npm install vuex@next --save

Create a store path under src and create index.js under store

import { createStore } from 'vuex'

export default createStore({
  state () {
    return {
      username: ''
    }
  },
  mutations:
    setUserName (state, payload) {
      state.username = payload
    }
  }
})

Use store in main.js

import vuex from './store'
//...
app.use(vuex)

Importing Axios

For network requests, axios is used here. First, install axios

npm i axios

Create an api directory under the src directory, create axios.js under the api path, and configure the axios instance

// axios.js
import axios from 'axios'
// import config from '../../config'
import { useRouter } from 'vue-router'

export default function () {
  // 1. When sending a request, if there is a token, it needs to be attached to the request header const token = localStorage.getItem('token')
  let instance = axios

  if (token) {
    instance = axios.create({
      // baseURL: config.server,
      headers: {
        authorization: 'Bearer ' + token
      }
    })
  }

  const router = useRouter()
  instance.interceptors.response.use(
    (resp) => {
      // 2. When responding, if there is a token, save the token locally (localstorage)
      if (resp.data.data.token) {
        localStorage.setItem('token', resp.data.data.token)
      }
      // 3. When responding, if the response message code is 403 (no token, token invalid), delete the token locally
      if (resp.data.code === 403) {
        localStorage.removeItem('token')
        localStorage.removeItem('username')
        router.push({ name: 'Login' })
      }
      return resp
    },
    (err) => {
      return Promise.reject(err)
    }
  )

  return instance
}

Create index.js under the api path and write the api

import request from './axios.js'
import config from '../../config'
export default {
  // Login login (params) {
    return request().post(`${config.server}/login`, params)
  },
  // Get the user list getUserList (params) {
    return request().get(`${config.server}/user/list`, {
      params: params
    })
  },
  // Add a user createUser (params) {
    return request().post(`${config.server}/user/`, params)
  },
  //...

Next, we use the composition API of vue3 to develop components. Here is an example of the development of a User module:

<template>
  <div class="user-wrap">
      <el-button
        class="create-btn"
        type="success"
        size="small"
      @click="handleCreate">Add user+</el-button>
      <el-table
        :data="tableData"
        style="width: 100%">
        <el-table-column
            label="Username"
            prop="username">
        </el-table-column>
        <el-table-column
            label="Password"
            prop="password">
        </el-table-column>
        <el-table-column
            align="right">
            <template #header>
                <el-input
                v-model="search"
                @blur="searchUser"
                size="mini"
                placeholder="Enter username to search"/>
            </template>
            <template #default="scope">
                <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
                <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">Delete</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
      :hide-on-single-page="hideOnSinglePage"
      class="page-wrap"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount">
    </el-pagination>
    <el-dialog title="User Information" v-model="dialogFormVisible">
        <el-form :model="form">
            <el-form-item label="Username" :label-width="formLabelWidth">
                <el-input v-model="form.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="Password" :label-width="formLabelWidth">
                <el-input v-model="form.password" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">Cancel</el-button>
                <el-button type="primary" @click="confirmUser">Confirm</el-button>
            </span>
        </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import api from '../../../api/index'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  setup () {
    let status = ''
    let userId = null
    const formLabelWidth = ref('120px')

    // Get user list const tableData = ref([])
    async function getList (params) {
      const res = await api.getUserList(params)
      if (res.data.success) {
        tableData.value = res.data.data.userList
        totalCount.value = res.data.data.count
        search.value = ''
      } else {
        ElMessage.error('Failed to get user list:' + res.data.msg)
      }
    }
    getList()

    const form = ref({
      username: '',
      password: ''
    })

    const dialogFormVisible = ref(false)

    // Submit user information async function confirmUser () {
      // Verify that the information is complete if (!(form.value.username && form.value.password)) {
        ElMessage.error('Incomplete form information')
        return
      }
      switch (status) {
        case 'create':
          createUser(form.value)
          break
        case 'edit':
          updateUser(userId, form.value)
          break
      }
    }

    // Add user async function handleCreate () {
      form.value = {
        username: '',
        password: ''
      }
      dialogFormVisible.value = true
      status = 'create'
    }
    // Add user information async function createUser (params) {
      const res = await api.createUser(params)
      if (res.data.success) {
        getList()
        ElMessage.success({
          message: 'Added successfully',
          type: 'success'
        })
        dialogFormVisible.value = false
      } else {
        ElMessage.error('Add failed:' + res.data.msg)
      }
    }

    // Edit user async function handleEdit (index, row) {
      console.log(index, row)
      dialogFormVisible.value = true
      status = 'edit'
      form.value.username = row.username
      form.value.password = row.password
      userId = row.id
    }
    // Modify user information async function updateUser (id, params) {
      const res = await api.updateUser(id, params)
      if (res.data.success) {
        ElMessage.success({
          message: 'Modification successful',
          type: 'success'
        })
        getList()
        dialogFormVisible.value = false
      } else {
        ElMessage.error('Modification failed: ' + res.data.msg)
      }
    }

    // Delete user const handleDelete = async (index, row) => {
      ElMessageBox.confirm('This operation will permanently delete the user, do you want to continue?', 'Prompt', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(async () => {
        await delUser(row.id)
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: 'Deleted'
        })
      })
    }
    // Delete user information async function delUser (id) {
      const res = await api.delUser(id)
      if (res.data.success) {
        getList()
        ElMessage.success({
          type: 'success',
          message: 'Deleted successfully!'
        })
      } else {
        ElMessage.error('Delete failed: ' + res.data.msg)
      }
    }

    // Search user const search = ref('')
    async function searchUser () {
      currentPage.value = 1
      pageSize.value = 10
      if (search.value === '') {
        getList({ pageindex: currentPage.value, pagesize: pageSize.value })
        return
      }
      currentPage.val = 1
      const res = await api.findUserByUsername({ username: search.value })
      if (res.data.success) {
        tableData.value = res.data.data.userList
        ElMessage.success({
          message: 'Search successful',
          type: 'success'
        })
      } else {
        ElMessage.error('Modification failed: ' + res.data.msg)
      }
    }

    // Paging related const totalCount = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    function handleSizeChange (val) {
      pageSize.value = val
      getList({ pageindex: currentPage.value, pagesize: val })
    }
    function handleCurrentChange (val) {
      currentPage.value = val
      getList({ pageindex: val, pagesize: pageSize.value })
    }
    // Hide the paging plugin if there are more than one page const hideOnSinglePage = computed(() => {
      return totalCount.value <= 10
    })

    return {
      tableData,
      search,
      dialogFormVisible,
      form,
      formLabelWidth,
      createUser,
      handleEdit,
      handleDelete,
      confirmUser,
      handleCreate,
      searchUser,
      currentPage,
      totalCount,
      handleSizeChange,
      handleCurrentChange,
      pageSize,
      hideOnSinglePage
    }
  }
}
</script>

<style lang="scss" scoped>
    .user-wrap{
        width: 100%;
        min-width: 500px;
        .create-btn{
            margin-bottom: 10px;
            display: flex;
            justify-content: flex-end;
        }
        .page-wrap{
            margin-top: 10px;
        }
    }
</style>

This is the end of this article about the steps to build the vite+vue3+element-plus project. For more relevant vite building vue3+ElementPlus content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vite builds projects and supports micro frontends
  • This article will show you what Vite does to the browser's request
  • Vite+Electron to quickly build VUE3 desktop applications
  • How to add Vite support to old Vue projects
  • Vite2.0 Pitfalls
  • Vue3.0+vite2 implements dynamic asynchronous component lazy loading
  • Implementation of vite+vue3.0+ts+element-plus to quickly build a project
  • Learn the principles of Vite

<<:  Detailed tutorial on installing Docker and nvidia-docker on Ubuntu 16.04

>>:  Detailed explanation of how to implement secondary cache with MySQL and Redis

Recommend

Javascript Basics: Detailed Explanation of Operators and Flow Control

Table of contents 1. Operator 1.1 Arithmetic oper...

A brief introduction to the simple use of CentOS7 firewall and open ports

Overview (official has more detailed description)...

A brief discussion on JS packaging objects

Table of contents Overview definition Instance Me...

The url value of the src or css background image is the base64 encoded code

You may have noticed that the src or CSS backgroun...

JavaScript macrotasks and microtasks

Macrotasks and Microtasks JavaScript is a single-...

Nginx reverse proxy and load balancing practice

Reverse Proxy Reverse proxy refers to receiving t...

Alibaba Cloud Server Domain Name Resolution Steps (Tutorial for Beginners)

For novices who have just started to build a webs...

Teach you the detailed process of installing DOClever with Docker Compose

Table of contents 1. What is Docker Compose and h...

Detailed steps for remote deployment of MySQL database on Linux

Linux remote deployment of MySQL database, for yo...

How to quickly modify the host attribute of a MySQL user

When you log in to MySQL remotely, the account yo...

How to match the size of text in web design: small text, big experience

With the rise of mobile terminals such as iPad, p...

translate(-50%,-50%) in CSS achieves horizontal and vertical centering effect

translate(-50%,-50%) attributes: Move it up and l...

Summary of experience in using div box model

Calculation of the box model <br />Margin + ...