欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vite+vue3+element-plus項目搭建的方法步驟

 更新時間:2021年06月08日 09:03:55   作者:wkArtist  
因為vue3出了一段時間了,element也出了基于vue3.x版本的element-plus,vite打包聽說很快,嘗試一下,感興趣的可以了解一下

使用vite搭建vue3項目

通過在終端中運(yùn)行以下命令,可以使用 Vite 快速構(gòu)建 Vue 項目。

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

引入Element Plus

安裝Element Plus:

npm install element-plus --save

main.js中完整引入 Element Plus:

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')

引入SCSS

執(zhí)行命令安裝sass, npm i sass -D, 然后在vue文件的style標(biāo)簽下加入lang="scss"即可,這些與以前vue2都是一樣的。

npm i sass -D

引入eslint

安裝eslint

npm i eslint -D

使用eslint對本項目進(jìn)行初始化

npx eslint --init

按照提示進(jìn)行設(shè)置,這是我選擇的設(shè)置

引入vue-router

安裝Vue Router 4

npm install vue-router@4

在src目錄下新建router文件夾,并在router下新建index.js進(jìn)行路由配置

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
})

在main.js下使用該中間件

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

引入vuex

安裝vuex

npm install vuex@next --save

在src下創(chuàng)建store路徑,并在store下創(chuàng)建index.js

import { createStore } from 'vuex'

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

在main.js下使用store

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

引入axios

對于網(wǎng)絡(luò)請求,這里使用axios,首先安裝axios

npm i axios

在src目錄下創(chuàng)建api目錄,并在api路徑下創(chuàng)建axios.js,配置axios實例

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

export default function () {
  // 1. 發(fā)送請求的時候,如果有token,需要附帶到請求頭中
  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. 響應(yīng)的時候,如果有token,保存token到本地(localstorage)
      if (resp.data.data.token) {
        localStorage.setItem('token', resp.data.data.token)
      }
      // 3. 響應(yīng)的時候,如果響應(yīng)的消息碼是403(沒有token,token失效),在本地刪除token
      if (resp.data.code === 403) {
        localStorage.removeItem('token')
        localStorage.removeItem('username')
        router.push({ name: 'Login' })
      }
      return resp
    },
    (err) => {
      return Promise.reject(err)
    }
  )

  return instance
}

在api路徑下創(chuàng)建index.js編寫api

import request from './axios.js'
import config from '../../config'
export default {
  // 登錄
  login (params) {
    return request().post(`${config.server}/login`, params)
  },
  // 獲取用戶列表
  getUserList (params) {
    return request().get(`${config.server}/user/list`, {
      params: params
    })
  },
  // 添加一個用戶
  createUser (params) {
    return request().post(`${config.server}/user/`, params)
  },
  //...

接下來使用vue3的composition api進(jìn)行組件的開發(fā),這里列舉一個User模塊的開發(fā):

<template>
  <div class="user-wrap">
      <el-button
        class="create-btn"
        type="success"
        size="small"
      @click="handleCreate">新增用戶 +</el-button>
      <el-table
        :data="tableData"
        style="width: 100%">
        <el-table-column
            label="用戶名"
            prop="username">
        </el-table-column>
        <el-table-column
            label="密碼"
            prop="password">
        </el-table-column>
        <el-table-column
            align="right">
            <template #header>
                <el-input
                v-model="search"
                @blur="searchUser"
                size="mini"
                placeholder="輸入用戶名搜索"/>
            </template>
            <template #default="scope">
                <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">編輯</el-button>
                <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">刪除</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="用戶信息" v-model="dialogFormVisible">
        <el-form :model="form">
            <el-form-item label="用戶名" :label-width="formLabelWidth">
                <el-input v-model="form.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密碼" :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">取 消</el-button>
                <el-button type="primary" @click="confirmUser">確 定</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')

    // 獲取用戶列表
    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('獲取用戶列表失敗:' + res.data.msg)
      }
    }
    getList()

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

    const dialogFormVisible = ref(false)

    // 提交用戶信息
    async function confirmUser () {
      // 驗證信息是否齊全
      if (!(form.value.username && form.value.password)) {
        ElMessage.error('表單信息不全')
        return
      }
      switch (status) {
        case 'create':
          createUser(form.value)
          break
        case 'edit':
          updateUser(userId, form.value)
          break
      }
    }

    // 添加用戶
    async function handleCreate () {
      form.value = {
        username: '',
        password: ''
      }
      dialogFormVisible.value = true
      status = 'create'
    }
    // 添加用戶信息
    async function createUser (params) {
      const res = await api.createUser(params)
      if (res.data.success) {
        getList()
        ElMessage.success({
          message: '添加成功',
          type: 'success'
        })
        dialogFormVisible.value = false
      } else {
        ElMessage.error('添加失?。? + res.data.msg)
      }
    }

    // 編輯用戶
    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
    }
    // 修改用戶信息
    async function updateUser (id, params) {
      const res = await api.updateUser(id, params)
      if (res.data.success) {
        ElMessage.success({
          message: '修改成功',
          type: 'success'
        })
        getList()
        dialogFormVisible.value = false
      } else {
        ElMessage.error('修改失?。? + res.data.msg)
      }
    }

    // 刪除用戶
    const handleDelete = async (index, row) => {
      ElMessageBox.confirm('此操作將永久刪除該用戶, 是否繼續(xù)?', '提示', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await delUser(row.id)
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消刪除'
        })
      })
    }
    // 刪除用戶信息
    async function delUser (id) {
      const res = await api.delUser(id)
      if (res.data.success) {
        getList()
        ElMessage.success({
          type: 'success',
          message: '刪除成功!'
        })
      } else {
        ElMessage.error('刪除失?。? + res.data.msg)
      }
    }

    // 搜索用戶
    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: '搜索成功',
          type: 'success'
        })
      } else {
        ElMessage.error('修改失?。? + res.data.msg)
      }
    }

    // 分頁相關(guān)
    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 })
    }
    // 超過一頁就隱藏分頁插件
    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>

到此這篇關(guān)于vite+vue3+element-plus項目搭建的方法步驟的文章就介紹到這了,更多相關(guān)vite搭建vue3+ElementPlus內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

  • NUXT SSR初級入門筆記(小結(jié))

    NUXT SSR初級入門筆記(小結(jié))

    這篇文章主要介紹了NUXT SSR初級入門筆記(小結(jié)),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • Vue3中操作ref的四種使用方式示例代碼(建議收藏)

    Vue3中操作ref的四種使用方式示例代碼(建議收藏)

    這篇文章主要介紹了Vue3中操作ref的四種使用方式示例代碼(建議收藏),本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-04-04
  • Vue項目中安裝依賴npm?install一直報錯的解決過程

    Vue項目中安裝依賴npm?install一直報錯的解決過程

    這篇文章主要給大家介紹了關(guān)于Vue項目中安裝依賴npm?install一直報錯的解決過程,要解決NPM安裝依賴報錯,首先要分析出錯誤的原因,文中將解決的過程介紹的非常詳細(xì),需要的朋友可以參考下
    2023-05-05
  • Vue瀏覽器緩存sessionStorage+localStorage+Cookie區(qū)別解析

    Vue瀏覽器緩存sessionStorage+localStorage+Cookie區(qū)別解析

    這篇文章主要介紹了Vue瀏覽器緩存sessionStorage+localStorage+Cookie區(qū)別解析,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-09-09
  • Mock.js在Vue項目中的使用小結(jié)

    Mock.js在Vue項目中的使用小結(jié)

    這篇文章主要介紹了Mock.js在Vue項目中的使用,在vue.config.js中配置devServer,在before屬性中引入接口路由函數(shù),詳細(xì)步驟跟隨小編通過本文學(xué)習(xí)吧
    2022-07-07
  • VUE2舊項目重新安裝依賴后@vue/compiler-sfc編譯報錯問題

    VUE2舊項目重新安裝依賴后@vue/compiler-sfc編譯報錯問題

    在VUE2舊項目中重新安裝依賴后,如果遇到@vue/compiler-sfc編譯報錯,首先需要檢查package.json文件中的Vue版本是否升級到2.7版本,2.7版本的編譯插件不再支持/deep/這種樣式穿透,版本^和~的區(qū)別在于^只能鎖住第一位數(shù)
    2025-01-01
  • 在vue中使用image-webpack-loader實例

    在vue中使用image-webpack-loader實例

    這篇文章主要介紹了在vue中使用image-webpack-loader實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • Vue路由跳轉(zhuǎn)的4種方式小結(jié)

    Vue路由跳轉(zhuǎn)的4種方式小結(jié)

    本文主要介紹了Vue路由跳轉(zhuǎn)的4種方式小結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06
  • vue-cli 如何打包上線的方法示例

    vue-cli 如何打包上線的方法示例

    這篇文章主要介紹了vue-cli 如何打包上線的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-05-05
  • Vue編寫自定義Plugin詳解

    Vue編寫自定義Plugin詳解

    這篇文章主要介紹了Vue編寫自定義Plugin詳解,在Vue開發(fā)中,我們經(jīng)常需要使用一些第三方庫或功能性模塊,Vue插件就是一種將這些庫或模塊集成到Vue應(yīng)用中的方式,插件是Vue.js提供的一種機(jī)制,用于擴(kuò)展Vue的功能,需要的朋友可以參考下
    2023-08-08

最新評論