jck28 - 小柒 - 前端开发 - 前端UI组件开发 Element Plus

一,UI 组件库-Element Plus

1.1 简介

image
image

1.2 安装

1.3 使用element plus

image

项目中注册使用lment plus

  • (1)main.js文件添加lelment plus
// import './assets/main.css'

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
// 导入element-plus
import ElementPlus from 'element-plus'
import "element-plus/dist/index.css"

// 使用路由和ElementPlus
createApp(App).use(router).use(ElementPlus).mount('#app')

// createApp(App).mount('#app')

1.4 组件API

image

二,基础组件

2.1 按钮组件

2.1.1 简介

image
image
image

2.1.2 代码示例

  • Ep.vue组件
<script setup>
    // import {ref} from 'vue'
    // const msg = ref("hello world!")
</script>

<template>
    <div>
        <el-button type="primary" >普通按钮样式</el-button>
    </div>
    <br>
<!-- 按钮类型 -->
    <div>
        <el-button type="primary" >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>
    </div>
    <br>
    <!-- 圆名按钮 -->
    <div>
        <el-button round> 普通圆名按钮</el-button>
     <el-button type="primary" round>圆名按钮 </el-button>
    </div>
    <br>
    <!-- 圆形按钮 -->
    <div>
        <el-button circle> </el-button>
        <el-button type="success" circle> 圆形按钮</el-button>
    </div>
    <br>
    <!-- 加载样式的按钮 -->
    <div>
        <el-button type="danger" loading></el-button>
    </div>
    <br>
    <!-- 禁用状态按钮 -->
    <div>
        <el-button type="primary" disabled>禁用状态按钮</el-button>
    </div>
    <br>
    <!-- 更改按钮尺寸 -->
    <div>
        <el-button type="primary" size="small">小按钮</el-button>
        <el-button type="primary" size="medium">中等按钮</el-button>
        <el-button type="primary">默认按钮</el-button>  
        <el-button type="primary" size="large">大按钮</el-button>
    </div>
    <br>
    <!-- 按钮组 -->
    <div>
        <el-button-group>
            <el-button type="success">1</el-button>
            <el-button type="success">2</el-button>
            <el-button type="success">3</el-button>
            <el-button type="success">4</el-button>
        </el-button-group>
    </div>

</template>

2.2 Container布局容器

2.2.1 简介

image

2.2.2 代码示例

  • Epcontainer.vue组件
<template>
    <el-container>
        <el-header>Header</el-header>
        <el-container>
            <el-aside width="200px">Aside</el-aside>
            <el-main>Main</el-main>
        </el-container>
        <el-footer>footer</el-footer>
    </el-container>

    <hr>

    <el-container>
        <el-header>Header</el-header>
        <el-container>
            <el-aside width="200px">Aside</el-aside>
            <el-container>
                <el-main>Main</el-main>
                <el-footer>footer</el-footer>
            </el-container>
        </el-container>
    </el-container>

</template>

<style>
    hr{
        margin: 100px 0;
    }
    .el-header,
    .el-footer{
        background-color:aqua;
        color: #333;
        text-align: center;
        line-height: 60px
    }
    .el-aside{
        background-color:#588ecb;
         color: #333;
        text-align:center;
        line-height: 200px
    }
    .el-main{
        background-color:#f0f2f5;
         color: #333;
        text-align:center;
        line-height: 160px
    }
</style>

2.3 Icon图标

2.3.1 简介

image
image

2.3.2 图标组件安装注册

  • 在项目根目录下安装依赖:

    • 安装命令:npm install @element-plus/icons-vue
  • 在main.js文件进行注册

// import './assets/main.css'

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
// 导入element-plus
import ElementPlus from 'element-plus'
import "element-plus/dist/index.css"
import * as ElementPlusIcons from '@element-plus/icons-vue'

const app = createApp(App)
// 将图标组件进行全局注册
for(const [key,component] of Object.entries(ElementPlusIcons)){
    app.component(key,component)
}

// 使用路由和ElementPlus
app.use(router).use(ElementPlus).mount('#app')

2.3.3 导入图标组件

image

2.3.4 图标创建和使用

<script setup>
// 在使用位置导入图标名
    import {
        Check,
        Delete,
        Edit,
        Message,
        Search,
        Star,
        Share
    } from "@element-plus/icons-vue"
    import { ref } from "vue"

    const size = ref("35px")
    const clolor = ref("red")

</script>

<template>
    <!-- <div> -->
        <!-- 直接使用 -->
        <!-- <Check />
        <Delete />
        <Edit />
        <Message /> -->
    <!-- </div> -->
    <!-- 由于SVG图标默认不携带任何属性,需要设置显示样式 -->
    <div style="font-size:40px">
        <Check style="width:24px; height:24px; margin-right: 8px" />
        <Edit style="width:24px; height:24px; margin-right: 8px" />
        <Delete style="width:1em; height:1em; margin-right: 8px" />
        <Message style="width:1em; height:1em; margin-right: 8px" />
    </div>

    <!-- 从父元素中获取属性 -->
    <div style="font-size:40px">
        <Check style="width:1em; height:1em; margin-right: 8px" />
        <Edit style="width:1em; height:1em; margin-right: 8px" />
        <Delete style="width:1em; height:1em; margin-right: 8px" />
        <Message style="width:1em; height:1em; margin-right: 8px" />
    </div>

    <!-- 使用图标组件设置 -->
    <div>
        <!-- 设置图标大小与颜色 -->
           <el-icon size="30" color="blue">
                <Edit />
          </el-icon>
        <!-- 使用响应式变量设置图标大小与颜色 -->
        <el-icon :size="size" :color="clolor">
            <Delete />
        </el-icon>
    </div>
    <!-- 使用el-button组件的:icon属性并引入对应的图标组件创建带图标的按钮 -->
    <div>
        <el-button :icon="Search"></el-button>
        <el-button type="primary" :icon="Edit"></el-button>
        <el-button type="success" :icon="Check" round></el-button>
        <el-button type="info" :icon="Message" round></el-button>
        <el-button type="warning" :icon="Star" circle></el-button>
        <el-button type="danger" :icon="Delete" circle></el-button>
    </div>
</template>

三,表单组件

3.1 简介

image
image
image
image
image
image

3.2 代码示例

  • (1)表单使用方式(EpForm.vue组件)
<script setup>
    import { ref } from 'vue'

    const data = ref({username:" ", password:" "})
    const onSubmit = () =>{
        console.log(data.value)
    }
</script>


<template>
<!-- 典型表单使用方式 -->
    <el-form :model="data" style="width: 300px" label-width="70px" label-position="left">
        <el-form-item label="用户名:">
            <el-input v-model="data.username" aria-placeholder="请输入用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码:">
            <el-input v-model="data.password"  type="password" aria-placeholder="请输入密码" clearable></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSubmit">登陆</el-button>
        </el-form-item>
    </el-form>

    <!-- 行内表单使用方式:inline -->
    <el-form :inline="true" :model="data"  label-width="70px" label-position="left">
        <el-form-item label="用户名:">
            <el-input v-model="data.username" aria-placeholder="请输入用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码:">
            <el-input v-model="data.password"  type="password" aria-placeholder="请输入密码" clearable></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSubmit">登陆</el-button>
        </el-form-item>
    </el-form>
</template>
  • (2)输入框组件(EpFormInput.vue)
<script setup>
import { ref } from 'vue'
import {Calendar, Search} from "@element-plus/icons-vue"

const inputNormal = ref("adsagdfh")
const inputUn = ref("")
const inputClear = ref("")
const inputPwd = ref("")
const inputIconDate = ref("")
const inputIconSearch = ref("")
const inputTextarea = ref("")
const inputTextarea2 = ref("")
const inputStar1 = ref("")
const inputStar2 = ref("")
const inputStar3 = ref("")
</script>

<template>
    <el-form style="width: 500px">
        <!-- 基础用法 -->
        <el-input v-model="inputNormal" placeholder="请输入内容"></el-input>
        <el-divider />
        <!-- 禁用状态 -->
        <el-input v-model="inputUn" disabled placeholder="输入框禁用状态"></el-input>
        <el-divider />
        <!-- 输入框可清空 -->
        <el-input v-model="inputClear" clearable placeholder="可清空"></el-input>
        <el-divider />
        <!-- 密码框,可显示密码 -->
        <el-input v-model="inputPwd" type="password" placeholder="密码输入框" show-password></el-input>
        <el-divider />
        <!-- 带图标的输入框,选择日期和搜索 -->
        <el-input v-model="inputIconDate" placeholder="选择日期" :suffix-icon="Calendar"></el-input>
        <el-divider />
        <el-input v-model="inputIconSearch" placeholder="搜索" :prefix-icon="Search"></el-input>
        <el-divider />
        <!-- 文本域 -->
        <el-input v-model="inputTextarea" :row="2" type="textarea" placeholder="请输入内容"></el-input>
        <el-divider />
        <el-input v-model="inputTextarea2" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" placeholder="请输入内容"></el-input>
        <el-divider />
        <!-- 复合型输入框 -->
        <el-input v-model="inputStar1" placeholder="请输入url地址">
            <template #prepend>http://</template>
        </el-input>
        <el-divider />
        <el-input v-model="inputStar2" placeholder="请输入url地址">
            <template #append>.com</template>
        </el-input>
        <el-divider />
        <el-input v-model="inputStar3" placeholder="请输入URL地址">
            <template #prepend>http://</template>
            <template #append>.com</template>
        </el-input>

    </el-form>
</template>
  • (3)checkBox多选框组件
<script setup>
    import { ref } from 'vue'
    // 选中
    const checkNormal1 = ref(true)
    // 未选中
    const checkNormal2 = ref(false)
    const checkNormal3 = ref(false)
    // 禁用状态
    const checkDisabled = ref(false)
    // 多选框组,选中的项
    const checkList = ref(['selected and disabled', 'OptionA'])
    // 中间状态,实现全选
    const checkAll = ref(false)
    const isIndeterminate = ref(true)
    const cities = ["beijing","shanghai","guangzhou","shenzhen"]
    const checkCities = ref("beijing","shanghai")
    // 数量限制
    const options = ["年轻10岁","瘦20斤","中五百万","上清华","长高10厘米"]
    const mySelect = ref([])

    // 全选框响应方法,参数为全选框的状态值
    function handleCheckAllChange(val) {
        // 如果参数为真,则选中所有,否则清空
        checkCities.value = val? cities : []
        // 所有数据选中后,改变isIndeterminate的状态值
        isIndeterminate.value = false
    }

    // 参数为checkCities的当前值
    function handleCheckCitiesChange(val){
        // 获取当前选中的个数
        const checkCount = val.length
        // 将选中个数和选项个数比较的结果值赋给checkAll按钮的状态值
        checkAll.value = checkCount ===cities.length
        // 如果选中个数大于0小于所有选项,则isIndeterminate为不确定状态;小于0为空状态,等于length为全选状态
        isIndeterminate.value = checkCount > 0 && checkCount < cities.length
    }
</script>

<template>
    <!-- 基础用法 -->
    <div>
        <el-checkbox v-model="checkNormal1" label="Option large" size="large" />
        <el-checkbox v-model="checkNormal2" label="Option Normal" />
        <el-checkbox v-model="checkNormal3" label="Option small" size="small" />
    </div>
    <!-- 禁用状态 -->
    <el-checkbox v-model="checkDisabled" disabled >禁用状态</el-checkbox>
    <!-- 多选框组,适用于多个勾选框绑定到同一个数组, -->
    <el-checkbox-group v-model="checkList">
        <el-checkbox label="OptionA">A</el-checkbox>
        <el-checkbox label="OptionB">B</el-checkbox>
        <el-checkbox label="Disabled" disabled>C</el-checkbox>
        <el-checkbox label="selected and disabled" disabled>D</el-checkbox>
    </el-checkbox-group>
    <!-- 中间状态,用isIndeterminate属性表示checkbox的不确定状态,一般用于实现全选效果 -->
    <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
    <el-checkbox-group v-model="checkCities" @change="handleCheckCitiesChange">
        <el-checkbox v-for="city in cities" :key="city" :label="city"></el-checkbox>
    </el-checkbox-group>  
    <!-- 可选项目数量的限制,使用min和max属性  -->
    <el-checkbox-group v-model="mySelect" :min="1" :max="3">    
        <el-checkbox v-for="option in options" :key="option" :label="option">{{ option }}</el-checkbox>
    </el-checkbox-group>
</template>
  • (4)ratio单选框组件
<script setup>
    import { ref } from 'vue'
    const radioNormal = ref("1")
    const radioNormalLarge = ref("1")
    const radioDisable = ref("selected and disabled")
    const radios = ref("3")
    const handleRatio = (val) =>{
        console.log(val)
    }
</script>

<template>
    <!-- 基础使用 -->
    <el-radio v-model="radioNormal" label="1">1</el-radio>
    <el-radio v-model="radioNormal" label="2">2</el-radio>
    <br>
    <!-- 禁用状态 -->
    <el-radio v-model="radioDisable" label="disabled" disabled>option1</el-radio>
    <el-radio v-model="radioDisable" label="selected and disabled" disabled>option2</el-radio>
     <br>
    <!-- 单选框组 -->
    <el-radio-group v-model="radioNormalLarge">
        <el-radio label="1" size="large" >option1</el-radio>
        <el-radio label="2" size="large" >option2</el-radio>
    </el-radio-group>
     <br>
    <!-- 按钮样式组 -->
    <el-radio-group v-model="radios" :change="handleRatio">
        <el-radio-button :label="3">OptionA</el-radio-button>
        <el-radio-button :label="6">OptionB</el-radio-button>
        <el-radio-button :label="9">OptionC</el-radio-button>
    </el-radio-group>
</template>

四,数据展示组件

4.1 Table表格组件

image

  • 示例:EpTable组件
<script setup >
    const tableData = [
        {num:"01", case:"测试用例1", priority:"P0"},
        {num:"02", case:"测试用例2", priority:"P1"},
        {num:"03", case:"测试用例3", priority:"P2"}
    ]

    const handleEdit = (index,row) =>{
        console.log(index,row)
    }
    const handleDelete = (index,row) =>{
        console.log(index,row)
    }
</script>

<template>
    <el-table :data="tableData" style="width: 800px;">
        <el-table-colomn prop="num" label="编号" width="100"></el-table-colomn>
        <el-table-colomn prop="case" label="用例名称" width="280"></el-table-colomn>
        <el-table-colomn prop="priority" label="优先级" width="200"></el-table-colomn>
        <el-table-colomn lable="操作">
            <template #default="scope">
                <el-button size="small" type="success" @click="handleEdit(scope.$index,scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.$index,scope.row)">删除</el-button>
            </template>
        </el-table-colomn>
    </el-table>
</template>

4.2 Avatar 头像组件

image

<script setup>
    import { ref } from 'vue'
    import {UserFilled} from '@element-plus/icons-vue'      
    
    const errHandler = ref(true)
    const state = ref({
        circleUrl: 'https://img1.baidu.com/it/u=2223092495,2890927007&fm=253&fmt=auto&app=138&f=PNG?w=304&h=304',
        squareUrl: 'https://img1.baidu.com/it/u=2893147358,3393430132&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
        sizeList: ['small', 'default','large']
    })
</script>

<template>
    <!-- 基础用法,圆角矩形头像 -->
    <div>
        <el-avatar :size="120" :src="state.circleUrl"></el-avatar>
    </div>
    <div v-for="size in state.sizeList" :key="size">
        <el-avatar :size="size" :src="state.circleUrl"></el-avatar>
    </div>
    <!-- 方角矩形头像 -->
    <div>
        <el-avatar shape="square" :size="60" :src="state.squareUrl"></el-avatar>
    </div>
    <div v-for="size in state.sizeList" :key="size">
        <el-avatar shape="square" :size="size" :src="state.squareUrl"></el-avatar>
    </div>
    <!-- 文字头像 -->
    <div>
        <el-avatar >user</el-avatar>
    </div>
    <!-- 图片头像 -->
    <div>
        <el-avatar src="https://inews.gtimg.com/news_bt/OWvBqEB-jc6Q1r2UhKaeRr-uG6t39aEkVUds-OC0VNv4oAA/641" />
    </div>
    <!-- 图标头像 -->
    <div>
        <el-avatar :icon="UserFilled" />
    </div>
    <!-- 图片加载失败时的回退行为 -->
    <div class="demo-type">
        <el-avatar :size="100" src="https://empty" @error="errHandler">
            <img src="https://img-blog.csdnimg.cn/3ffc3a8d36a4440bbe800f45016a4d9d.png" />
        </el-avatar>
    </div>

</template>

4.3 Card卡片组件

image


<template>
    <!-- 简单卡片 -->
    <el-col :span="10">
        <el-card>
            <div v-for="i in 4" :key="i" class="text item">{{"List Item is" + i}}</div>
        </el-card>
    </el-col>
    <br>
    <!-- 完整卡片 -->
    <el-col :span="10">
        <el-card>
            <template #header>
            <div class="card-header">
                <span>Card Name</span>
                <el-button type="info">Operation</el-button>
            </div>
            </template>
            <div v-for="i in 4" :key="i" class="text item">{{"List Item is" + i}}</div>
            <template #footer>Footer Content</template>            
        </el-card>
    </el-col>
    <br>
    <!-- 图文卡片 -->
    <el-col :span="10">
        <el-card :body-style="{ padding: '0px' }">
            <img src="https://img-blog.csdnimg.cn/3ffc3a8d36a4440bbe800f45016a4d9d.png" class="image" />
            <div style="padding: 14px;">
                <span>Yammy Hunbeger</span>
                <div class="box">
                    <time class="time" >{{CurrentDate}}</time>
                    <el-button type="info">Operation</el-button>
                </div>
            </div>
        </el-card>
    </el-col>
    <!-- 卡片阴影效果,shadow属性值为always hover never -->
    <el-row :gutter="12">
        <el-col :span="8">
            <el-card shadow="always">Always</el-card>
        </el-col>
        <el-col :span="8">
            <el-card shadow="hover">Hover</el-card>
        </el-col>
        <el-col :span="8">
            <el-card shadow="never">Never</el-card>
        </el-col>
    </el-row>
</template>

<style scoped>
    .card-header{
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .image{
        width:100%;
        display: block;
    }

</style>

五,导航组件

5.1 Breadcrumb 面包屑导航

image

<script setup>
    import {ArrowRight} from '@element-plus/icons-vue'
</script>

<template>
    <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{path:'/home'}">Home</el-breadcrumb-item>
        <el-breadcrumb-item :to="{path:'/home/vue'}">Vue</el-breadcrumb-item>
        <el-breadcrumb-item :to="{path:'/home/vue/elementplus'}">Elementplus</el-breadcrumb-item>
        <el-breadcrumb-item :to="{path:'/home/vue/elementplus/breadcrumb'}">Breadcrumb</el-breadcrumb-item>
    </el-breadcrumb>
    <br>
    <!-- 图标分隔符 -->
     <el-breadcrumb separator-icon="ArrowRight">
        <el-breadcrumb-item ><a href="/home">Home</a></el-breadcrumb-item>
        <el-breadcrumb-item ><a href="/home/vue">Vue</a></el-breadcrumb-item>
        <el-breadcrumb-item><a href="/home/vue/elementplus">Elementplus</a></el-breadcrumb-item>
        <el-breadcrumb-item ><a href="/home/vue/elementplus/breadcrumb">Breadcrumb</a></el-breadcrumb-item>
     </el-breadcrumb>
</template>

5.2 Menu 菜单导航

  • 顶栏菜单
    image
<script lang="ts" setup>
import {ref} from 'vue'
const activeIndex = ref("1")
const handleSelect = (key:string, keyPath:string[]) => {
  console.log(key, keyPath)
}

</script>

    <!-- 顶部菜单 -->
<template>
    <el-menu mode="horizontal" :default-active="activeIndex" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b">
        <el-menu-item index="1">首页</el-menu-item>
        <el-menu-item index="2">财经</el-menu-item>
        <el-menu-item index="3">新闻</el-menu-item>
        <el-sub-menu index="4">
            <template #title>运动 </template>
            <el-menu-item index="4-1">篮球</el-menu-item>
            <el-menu-item index="4-2">足球</el-menu-item>
            <el-menu-item index="4-3">橄榄球</el-menu-item>
        </el-sub-menu>
        <el-menu-item index="5" disabled>汽车</el-menu-item>
    </el-menu>
</template>
  • 左右菜单
    image
<script lang="ts" setup>
import {ref} from 'vue'
const activeIndex = ref("1")
const handleSelect = (key:string, keyPath:string[]) => {
  console.log(key, keyPath)
}

<!-- 左右菜单 -->
<template>
    <el-menu mode="horizontal" :default-active="activeIndex" :ellipsis="false" @select="handleSelect">
        <el-menu-item index="0">
            <img  style="width:100px" src="https://img-blog.csdnimg.cn/3ffc3a8d36a4440bbe800f45016a4d9d.png" alt="element logo">
        </el-menu-item>
        <!-- 添加站位区域,将菜单挤到右边 -->
        <div class="placeholder_area"></div>
        <!-- 右侧的菜单 -->
         <el-menu-item index="1">Process Center</el-menu-item>
         <el-sub-menu index="2">
             <template #title>WorkSpace</template>
             <el-menu-item index="2-1">item one</el-menu-item>
             <el-menu-item index="2-2">item two</el-menu-item>
             <el-menu-item index="2-3">item three</el-menu-item>
             <el-sub-menu index="2-4">
                 <template #title>item four</template>
                 <el-menu-item index="2-4-1">Subitem one </el-menu-item>
                 <el-menu-item index="2-4-2">Subitem two</el-menu-item>
                 <el-menu-item index="2-4-3">Subitem three</el-menu-item>
             </el-sub-menu>
         </el-sub-menu>
    </el-menu>
</template>

<style scoped>
    .placeholder_area {
        flex: 1;
        /* background-color:red */
    }
</style>
  • 侧栏菜单
    image
<script lang="ts" setup>
import {ref} from 'vue'
import {Document,Menu,Location,Setting}  from '@element-plus/icons-vue'

const activeIndex = ref("1")
const handleOpen = (key:string, keyPath:string[]) => {
  console.log(key, keyPath)
}
const handleClose = (key:string, keyPath:string[]) => {
  console.log(key, keyPath)
}

</script>

<!-- 侧栏菜单 -->
<template>
    <el-col :span="4">
        <el-menu active-text-color="#ffd04b" background-color="#545c64" text-color="#fff" 
        :default-active="activeIndex" @open="handleOpen" @close="handleClose">
            <el-sub-menu index="1">
                <template #title>
                    <el-icon>
                        <Location />
                    </el-icon>
                    <span>Menu One</span>
                </template>
                <el-menu-item-group tittle="Group One">
                    <el-menu-item index="1-1">subItem one</el-menu-item>
                    <el-menu-item index="1-2">subItem two</el-menu-item>
                </el-menu-item-group>
                <el-menu-item-group title="Group Two">
                    <el-menu-item index="1-3">subItem three</el-menu-item>
                </el-menu-item-group>
                <el-sub-menu index="1-4">
                    <template #title>subItem four </template>
                    <el-menu-item index="1-4-1">subItem four-1</el-menu-item>
                </el-sub-menu>
            </el-sub-menu>
            <el-menu-item index="2">
                <el-icon>
                    <Menu />
                </el-icon>
                <span>Menu Two</span>
            </el-menu-item>

            <el-menu-item index="3" disabled>
                <el-icon> 
                    <Document />
                </el-icon>
                <span>Menu Three</span>
            </el-menu-item>

            <el-menu-item index="4">
                <el-icon> 
                    <Setting />
                </el-icon>
                <span>Menu four</span>
            </el-menu-item>
        </el-menu>
    </el-col>
</template>


  • 折叠面板菜单
    image
<script lang="ts" setup>
import {ref} from 'vue'
import {Document,Menu,Location,Setting}  from '@element-plus/icons-vue'

const activeIndex = ref("1")
const isCollapse = ref(true)
const handleOpen = (key:string, keyPath:string[]) => {
  console.log(key, keyPath)
}
const handleClose = (key:string, keyPath:string[]) => {
  console.log(key, keyPath)
}

</script>

<!-- 侧栏菜单 -->
<template>
    <el-col :span="4">
        <el-radio-group v-model="isCollapse" style="margin-bottom:20px">
            <el-radio-button :label="false">展开</el-radio-button>
            <el-radio-button :label="true">折叠</el-radio-button>
        </el-radio-group>
        <el-menu text-color="#fff" active-text-color="#ffd04b" background-color="#545c64"
        :default-active="activeIndex" :collapse="isCollapse" @open="handleOpen" @close="handleClose">
            <el-menu-item index="1">
                <el-icon><Location /></el-icon>
                <template #title>Navigator One</template>
            </el-menu-item>
            <el-menu-item index="2">
                <el-icon><Menu /></el-icon>
                <template #title>Navigator Two</template>
            </el-menu-item>
            <el-menu-item index="3">
                <el-icon> <Document /></el-icon>
                <template #title>Navigator Three</template>
            </el-menu-item>
            <el-menu-item index="4">
                <el-icon> <Setting /></el-icon>
                <template #title>Navigator Four</template>
            </el-menu-item>
        </el-menu>
    </el-col>
</template>
  • Dropdown下拉菜单
    image
<script setup>
import {ArrowDown,Check,CircleCheck,CirclePlus,CirclePlusFilled,Plus,}  from '@element-plus/icons-vue'

</script>

<!-- 下拉菜单 --> 
<template>
    <el-row>
        <el-col :span="8">
            <el-dropdown>
                <span>
                    悬浮下拉菜单 <el-icon> <arrow-down /></el-icon>
                </span>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item :icon="Plus">Actiopn 1</el-dropdown-item>
                        <el-dropdown-item :icon="CirclePlusFilled">Action 2</el-dropdown-item>
                        <el-dropdown-item :icon="CirclePlus">Action 3</el-dropdown-item>
                        <el-dropdown-item :icon="CircleCheck">Action 4</el-dropdown-item>
                        <el-dropdown-item :icon="Check">Action 5</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </el-col>

        <el-col :span="8">
            <el-dropdown trigger="click">
                <span>
                    单击触发下拉菜单 <el-icon> <arrow-down /></el-icon>
                </span>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item :icon="Plus">Actiopn 1</el-dropdown-item>
                        <el-dropdown-item :icon="CirclePlusFilled">Action 2</el-dropdown-item>
                        <el-dropdown-item :icon="CirclePlus">Action 3</el-dropdown-item>
                        <el-dropdown-item :icon="CircleCheck">Action 4</el-dropdown-item>
                        <el-dropdown-item :icon="Check">Action 5</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </el-col>

        <el-col :span="8">
            <el-dropdown trigger="contextmenu">
                <span>
                    右击触发下拉菜单 <el-icon> <arrow-down /></el-icon>
                </span>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item :icon="Plus">Actiopn 1</el-dropdown-item>
                        <el-dropdown-item :icon="CirclePlusFilled">Action 2</el-dropdown-item>
                        <el-dropdown-item :icon="CirclePlus">Action 3</el-dropdown-item>
                        <el-dropdown-item :icon="CircleCheck">Action 4</el-dropdown-item>
                        <el-dropdown-item :icon="Check">Action 5</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </el-col>
    </el-row>
</template>

六,反馈组件

6.1 Message消息提示

image

<script setup>
    import {ElMessage} from 'element-plus'
    // 默认样式
    const showMessage = () => {
        ElMessage("这是一个消息弹框提示")
    }
    const open1 = () => {
        ElMessage("这是一个普通的提示")
    }
   // 定制样式
    const open2 = () => {
        ElMessage({
            message: '成功的提示',
            type:'success'
        })
    }
    const open3 = () => {
        ElMessage({
            message: '警告的提示',
            type: 'warning',
            // 设置提示框关闭时间,为0则会一直显示,不关闭
            duration: 0,
            // 设置手动关闭
            showClose: true
        })
    }
    const open4 = () => {
        ElMessage.error('错误的提示')
    }
</script>

<template>
    <el-button @click="showMessage">弹出消息</el-button>

    <div>
        <el-button type="info" @click="open1">message</el-button>
        <el-button type="success" @click="open2">success</el-button>
        <el-button type="warning" @click="open3">warning</el-button>
        <el-button type="danger" @click="open4">error</el-button>
    </div>
</template>

6.2 MessageBox消息弹框

消息提示

image

确认消息

image

提交内容

image

代码示例

<script setup>
    import { ElMessage ,ElMessageBox } from 'element-plus'
    const open = () =>{
        ElMessageBox.alert('这是一条消息提示', 'title', {
            confirmButtonText: '确定',
            // action用来接收操作后的结果
            callback: (action) =>{
                ElMessage({
                    type:'info',
                    message: `action:${action}`
                })
            }
        })
    }

    const open1 = () =>{
        ElMessageBox.confirm('这是一条确认消息提示', 'title', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'  
        })
        .then(() => {
            ElMessage({
                type:'success',
                message: '创建成功'
            })
        })
        .catch(() =>{
            ElMessage({
                type:'info',
                message: '取消创建'
            })
        }) 
    }

    const open2 = () =>{
        ElMessageBox.prompt('Please input your e-mail', 'Tip', {
            confirmButtonText: 'confirm',
            cancelButtonText: 'cancel',
            inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
            inputErrorMessage: 'invalid Email'
            }
        )
        .then(({value}) =>{
            ElMessage({
                type:'success',
                message: `Your email is ${value}`
            })
        })
        .catch(() =>{
            ElMessage({
                type:'info',
                message: 'Input Canceled'
            })      
        })
    }
</script>

<template>
    <el-button type="success" @click="open">Click to open the message box</el-button>
    <br>
    <br>
    <el-button type="success" @click="open1">open the message box</el-button>
    <br>
    <br>
    <el-button type="success" @click="open2">open the message box</el-button>
</template>

6.3 Dialog对话框组件

image

<script lang="ts" setup>
    import { ref } from 'vue'
    import {ElMessageBox} from 'element-plus'
    const dialogVisible = ref(false)
    // 关闭按钮的处理方法
    const handleClose = (done: () => void) => {
        ElMessageBox.confirm('Are you sure to close the dialog?')
        .then(() => {
            done()
        })
        .catch(() => {})
    }

    const dialogFormVisible = ref(false)
    const form = ref({
        name: '',
        region: ''
    })
</script>

<template>
    <!-- 基本使用 -->
    <!-- <el-button type="success" @click="dialogVisible = true">Click to open dialog</el-button>
    <el-dialog v-model="dialogVisible" title="Tips" width="30%" :before-close="handleClose">
        <span>This is a dialog.</span> -->
        <!-- 使用插槽定制功能按钮 -->
        <!-- <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">Cancel</el-button>
                <el-button type="primary" @click="dialogVisible=false">Confirm</el-button>
            </span>
        </template>
    </el-dialog> -->
    
    <!-- 自定义内容 -->
     <el-button type="success" @click="dialogFormVisible = true">Open a form dialog</el-button>
     <el-dialog v-model="dialogFormVisible" title="shopping address" width="30%">
         <el-form :model="form" >
             <el-form-item label="Promotion name" label-width="140px">
                <el-input v-model="form.name" autocomplete="off"></el-input>
             </el-form-item>
             <el-form-item label="Zones" label-width="140px">
                <el-select v-model="form.region" placeholder="Please select a zone:">
                    <el-option label="zone no.1" value="Shanghai" />
                    <el-option label="zone no.2" value="Beijing" />
                </el-select>
             </el-form-item>
         </el-form>
         <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">Cancel</el-button>
                <el-button type="primary" @click="dialogFormVisible=false">Confirm</el-button>
            </span>
         </template>
     </el-dialog>
</template>

七,Vue 使用 axios 访问 api

7.1 简介和安装

image
image

7.2 发送请求

image
image
image

7.3 代码示例(NetAxios.vue组件)

<script setup>
    import axios from 'axios'

    function sendGetRequest() {
        var url = 'https://httpbin.ceshiren.com/get?id=123&name=demi'
        axios.get(url)
           .then((response) =>{
                alert("GET请求成功")
                console.log(response)
           })
           .catch((error) => {
                alert("GET请求失败")
                console.log(error)
            })
    }

    const sendGetRequestWithParams =() =>{
        axios.get('https://httpbin.ceshiren.com/get',{params:{id:234,name:'sammy'}})
        .then((response) =>{
            alert("GET请求成功")
            console.log(response)
        })
        .catch((error) => {
            alert("GET请求失败")
            console.log(error)
        })
    }

    const sendPostRequest = () =>{
        axios.post('https://httpbin.ceshiren.com/post')
        .then((response) =>{
            alert("POST请求成功")
            console.log(response)
        })
        .catch((error) => {
            alert("POST请求失败")
            console.log(error)
        })
    }

    const sendJsonRequest = () =>{
        axios.post('https://httpbin.ceshiren.com/post',{id:1134,name:"Alex",age:35})
        .then((response) =>{
            alert("POST请求成功")
            console.log(response)
        })
        .catch((error) => {
            alert("POST请求失败")
            console.log(error)
        })
    }

    const sendFormRequest = () =>{
        const formData = new FormData()
        formData.append("id",222)
        formData.append("name","Lily")
        formData.append("age",18)

         axios.post("https://httpbin.ceshiren.com/post",formData,{headers:{"Content-Type":"multipart/form-data"}})
         .then((response) =>{
            alert("POST请求成功")
            console.log(response)
        })
         .catch((error) => {
            alert("POST请求失败")
            console.log(error)
        })
    }

</script>

<template>
    <div>
        <h1>以GET方式发送请求</h1>
        <button @click="sendGetRequest">发送普通的get请求</button>
        <button @click="sendGetRequestWithParams">发送带参数的get请求</button>
    </div>

    <div>
        <h1>以POST方式发送请求</h1>
        <button @click="sendPostRequest">发送无参的post请求</button>
        <button @click="sendJsonRequest">发送带json参数的post请求</button>
        <button @click="sendFormRequest">发送form表单请求</button>
    </div>
</template>

八,网络请求封装优化

8.1 提取基础信息

image

  • http.js文件:
import axios from 'axios'

const instance = axios.create({
    baseURL:"https://httpbin.ceshiren.com",
    timeout:5000,
    headers:{
        "Content-Type":"application/json"
    }
})

export default instance

8.2 封装请求方法

  • 在api文件夹中,新建api.js文件,根据请求方式封装不同的请求方法
// 导入instance实例
import instance from './http'

const api = {
    get(reqUrl,reqParams){
        return instance({
            url: reqUrl,
            method: "get",
            params: reqParams
        })
    },
    post(reqUrl,reqData){
        return instance({
            url: reqUrl,
            method: "post",
            data: reqData
        })
    },
    put(reqUrl,reqData){
        return instance({
            url: reqUrl,
            method: "put",
            data: reqData
        })
    },
    delete(reqUrl,reqData){
        return instance({
            url: reqUrl,
            method: "delete",
            data: reqData
        })
    }
}

export default api

8.3 挂载到全局实例

  • 在main.js中将封装好的网络请求实例挂载到全局对象window上。
// 导入api实例
import api from '../api/api'
// 将api实例挂载到window全局对象上
window.$api = api

8.4 组件中应用(UseNetTools.vue文件)

  • 将网络请求挂载到了window对象中,所以在组件中使用网络请求方法时,可以直接进行使用。
<script setup>
    const sendGetReq = () =>{
        // 通过window对象挂载的api实例调用请求方法
        window.$api.get("/get",{params:{id:185}})
        .then((result) =>{
            console.log(result)
        })
        .catch((err) =>{
            console.log(err)
        })
    }

    const sendPostReq = () =>{
        // 简化使用,可以直接使用$api请求
        $api.post("/post",{id:155,name:"张三"})
        .then((result) =>{
            console.log(result)
        })
        .catch((err) =>{
            console.log(err)    
        })
    }
</script>

<template>
    <div>
        <button @click="sendGetReq">发起GET请求</button>
        <button @click="sendPostReq">发起POST请求</button>
    </div>
</template>

8.5 优点

image