1.个人中心,用户信息在初始化为空的时候,回显用户姓名
<el-form-item label="姓名" prop="name">
<!-- form {
{
form }} -->
<el-input
v-if="form.name === ''"
v-model="uName"
:disabled="isEdit"
/>
<el-input v-else v-model="form.name" :disabled="isEdit" />
</el-form-item>
------------------------------
从store中取出get `uName: store.getters['user/username'],`
在点击【提交按钮】 判断 当前【姓名】字段是否用户更改过,若没有更改将当前form.name赋值为uName(从localstorage中取出的值)
onSubmit() {
if (this.form.name === '') {
this.form.name = this.uName
}
this.$refs['form'].validate(async (valid) => {
if (valid) {
await updateUserInfo(this.form, this.uid)
ElMessage.success({
message: '更新成功~',
type: 'success',
})
this.setAvatar(this.form.avatar)
this.setUserName(this.form.name)
this.isEdit = true
} else {
return false
}
})
},
2.父子组件调用ref
父组件:绑定【edit】组件,在子组件中fetch-data的时候调用fetchData
<keyDetail ref="edit" @fetch-data="fetchData" />
-----------------------------------------------------------------
子组件:
export default {
name: 'KeyAdd',
emits: ['fetchData'],
data() {
return {
},
}
},
methods: {
async showAdd() {
this.dialogFormVisible = true
const r = await getCouponsList()
this.couponConnectList = r.result
},
close() {
this.$refs['form'].resetFields()
this.ruleForm = this.$options.data().ruleForm
this.dialogFormVisible = false
},
save() {
this.$refs['form'].validate(async (valid) => {
if (valid) {
await addOneSdkCode(this.form)
this.$baseMessage(
'添加成功!',
'success',
false,
'vab-hey-message-success'
)
this.$emit('fetchData')
this.close()
} else {
return false
}
})
},
},
}
3.页面跳转示例
父组件:
<template>
<div class="comprehensive-table-container">
<el-button type="primary" @click="onTest">测试跳转详情</el-button>
</div>
</template>
<script>
import {
useRouter } from 'vue-router'
export default {
setup() {
const router = useRouter()
const onTest = () => {
router.push({
path: '/course/edit',
query: {
title: '课程管理' },
})
}
return {
onTest }
},
}
</script>
子组件
<template>
<section class="edit-container">
<el-page-header
:content="'【' + $route.query.title + '】详情页面'"
@back="goBack"
/>
</section>
</template>
<script>
import {
useStore } from 'vuex'
import {
useRoute, useRouter } from 'vue-router'
import {
handleActivePath } from '@/utils/routes'
export default {
name: 'Edit',
setup() {
const store = useStore()
const route = useRoute()
const router = useRouter()
store.dispatch('tabs/changeTabsMeta', {
title: '详情页',
meta: {
icon: 'edit-line',
title: `${
route.query.title} 详情页`,
},
})
const goBack = () => {
store.dispatch('tabs/delVisitedRoute', handleActivePath(route, true))
router.push('/course/course-management')
}
return {
goBack }
},
}
</script>
el-autocomplete
远程搜索(从服务端搜索数据)
使用方法:
<template>
<el-autocomplete
v-model="state"
:fetch-suggestions="querySearchAsync"
placeholder="请输入内容"
@select="handleSelect"
></el-autocomplete>
</template>
<script>
import {
defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
setup() {
const restaurants = ref([]);
const loadAll = () => {
return [
{
value: "三全鲜食(北新泾店)", address: "长宁区新渔路144号" },
{
value: "Hot honey 首尔炸鸡(仙霞路)",
address: "上海市长宁区淞虹路661号",
},
{
value: "新旺角茶餐厅",
address: "上海市普陀区真北路988号创邑金沙谷6号楼113",
},
{
value: "泷千家(天山西路店)", address: "天山西路438号" },
{
value: "胖仙女纸杯蛋糕(上海凌空店)",
address: "上海市长宁区金钟路968号1幢18号楼一层商铺18-101",
},
{
value: "贡茶", address: "上海市长宁区金钟路633号" },
{
value: "豪大大香鸡排超级奶爸",
address: "上海市嘉定区曹安公路曹安路1685号",
},
{
value: "茶芝兰(奶茶,手抓饼)",
address: "上海市普陀区同普路1435号",
},
{
value: "十二泷町", address: "上海市北翟路1444弄81号B幢-107" },
{
value: "星移浓缩咖啡", address: "上海市嘉定区新郁路817号" },
{
value: "阿姨奶茶/豪大大", address: "嘉定区曹安路1611号" },
{
value: "新麦甜四季甜品炸鸡", address: "嘉定区曹安公路2383弄55号" },
{
value: "Monica摩托主题咖啡店",
address: "嘉定区江桥镇曹安公路2409号1F,2383弄62号1F",
},
{
value: "浮生若茶(凌空soho店)",
address: "上海长宁区金钟路968号9号楼地下一层",
},
{
value: "NONO JUICE 鲜榨果汁", address: "上海市长宁区天山西路119号" },
{
value: "CoCo都可(北新泾店)", address: "上海市长宁区仙霞西路" },
{
value: "快乐柠檬(神州智慧店)",
address: "上海市长宁区天山西路567号1层R117号店铺",
},
{
value: "Merci Paul cafe",
address: "上海市普陀区光复西路丹巴路28弄6号楼819",
},
{
value: "猫山王(西郊百联店)",
address: "上海市长宁区仙霞西路88号第一层G05-F01-1-306",
},
{
value: "枪会山", address: "上海市普陀区棕榈路" },
{
value: "纵食", address: "元丰天山花园(东门) 双流路267号" },
{
value: "钱记", address: "上海市长宁区天山西路" },
{
value: "壹杯加", address: "上海市长宁区通协路" },
{
value: "唦哇嘀咖",
address: "上海市长宁区新泾镇金钟路999号2幢(B幢)第01层第1-02A单元",
},
{
value: "爱茜茜里(西郊百联)", address: "长宁区仙霞西路88号1305室" },
{
value: "爱茜茜里(近铁广场)",
address:
"上海市普陀区真北路818号近铁城市广场北区地下二楼N-B2-O2-C商铺",
},
{
value: "鲜果榨汁(金沙江路和美广店)",
address: "普陀区金沙江路2239号金沙和美广场B1-10-6",
},
{
value: "开心丽果(缤谷店)",
address: "上海市长宁区威宁路天山路341号",
},
{
value: "超级鸡车(丰庄路店)", address: "上海市嘉定区丰庄路240号" },
{
value: "妙生活果园(北新泾店)", address: "长宁区新渔路144号" },
{
value: "香宜度麻辣香锅", address: "长宁区淞虹路148号" },
{
value: "凡仔汉堡(老真北路店)",
address: "上海市普陀区老真北路160号",
},
{
value: "港式小铺", address: "上海市长宁区金钟路968号15楼15-105室" },
{
value: "蜀香源麻辣香锅(剑河路店)", address: "剑河路443-1" },
{
value: "北京饺子馆", address: "长宁区北新泾街道天山西路490-1号" },
{
value: "饭典*新简餐(凌空SOHO店)",
address: "上海市长宁区金钟路968号9号楼地下一层9-83室",
},
{
value: "焦耳·川式快餐(金钟路店)",
address: "上海市金钟路633号地下一层甲部",
},
{
value: "动力鸡车", address: "长宁区仙霞西路299弄3号101B" },
{
value: "浏阳蒸菜", address: "天山西路430号" },
{
value: "四海游龙(天山西路店)", address: "上海市长宁区天山西路" },
{
value: "樱花食堂(凌空店)",
address: "上海市长宁区金钟路968号15楼15-105室",
},
{
value: "壹分米客家传统调制米粉(天山店)", address: "天山西路428号" },
{
value: "福荣祥烧腊(平溪路店)",
address: "上海市长宁区协和路福泉路255弄57-73号",
},
{
value: "速记黄焖鸡米饭",
address: "上海市长宁区北新泾街道金钟路180号1层01号摊位",
},
{
value: "红辣椒麻辣烫", address: "上海市长宁区天山西路492号" },
{
value: "(小杨生煎)西郊百联餐厅",
address: "长宁区仙霞西路88号百联2楼",
},
{
value: "阳阳麻辣烫", address: "天山西路389号" },
{
value: "南拳妈妈龙虾盖浇饭",
address: "普陀区金沙江路1699号鑫乐惠美食广场A13",
},
];
};
let timeout;
const querySearchAsync = (queryString, cb) => {
var results = queryString
? restaurants.value.filter(createFilter(queryString))
: restaurants.value;
clearTimeout(timeout);
timeout = setTimeout(() => {
cb(results);
}, 3000 * Math.random());
};
const createFilter = (queryString) => {
return (restaurant) => {
return (
restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
0
);
};
};
const handleSelect = (item) => {
console.log(item);
};
onMounted(() => {
restaurants.value = loadAll();
});
return {
restaurants,
state: ref(''),
querySearchAsync,
createFilter,
loadAll,
handleSelect,
};
},
});
</script>
<style></style>
5.Promise使用
Promise等待多个接口返回数据再执行操作
export async function useIndustry(industry) {
try {
const res = await industryList({
type: 7 })
if (res.status === 200) {
industry.value = res.result
}
return Promise.resolve(true)
} catch (err) {
return Promise.reject(err)
}
}
------------------------
export async function useEnterpriseLibrary({
total,
paramsQuery,
enterpriseLibrary,
}) {
try {
const {
cursor = 1,
limit = 10,
searchCount = true,
lableId = null,
companyName = null,
} = paramsQuery.value
const res = await enterpriseLibraryList({
cursor,
limit,
searchCount,
lableId,
companyName,
})
if (res.status === 200) {
total.value = res.result.total
enterpriseLibrary.value = res.result.records
}
return Promise.resolve(true)
} catch (err) {
return Promise.reject(err)
}
}
--------------------------------------
Promise.allSettled([
useIndustry(industry),
useEnterpriseLibrary({
total, paramsQuery, enterpriseLibrary }),
])
.then(() => nextTick(() => (loading.value = false)))
.catch((err) => console.error(err))
6.nextTick
7.路由重定向
vue3:
const logout = () => store.dispatch('user/logout')
const handleCommand = async (command) => {
switch (command) {
case 'logout':
await logout()
await router.push(toLoginRoute(route.path))
break
case 'personalCenter':
await router.push('/system/personal')
break
}
}
/**
* 获取当前跳转登录页的Route
* @param currentPath 当前页面地址
*/
export function toLoginRoute(currentPath) {
if (recordRoute && currentPath !== '/')
return {
path: '/login',
query: {
redirect: currentPath },
replace: true,
}
else return {
path: '/login', replace: true }
}
-------------------------
vue2:
async logout() {
await this.$store.dispatch('user/logout')
this.$router.push('/login')
},
8.格式化时间日期
<el-form-item label="开始时间">
<el-date-picker
v-model="dateRange"
clearable
end-placeholder="结束日期"
range-separator="至"
start-placeholder="开始日期"
type="datetimerange"
/>
</el-form-item>
<el-form-item>
<el-button
icon="el-icon-search"
native-type="submit"
type="primary"
@click="handleQuery"
>
查询
</el-button>
</el-form-item>
const handleQuery = () => {
queryForm.value.startTime =
dateRange.value && dateRange.value.length > 0
? parseTime(dateRange.value[0], '{y}-{m}-{d} {h}:{i}:{s}')
: null
queryForm.value.endTime =
dateRange.value && dateRange.value.length > 0
? parseTime(dateRange.value[1], '{y}-{m}-{d} {h}:{i}:{s}')
: null
emit('onEmitSearch', queryForm.value)
}
9.select
下拉框传参
<el-form-item v-if="form.redirectType === 2" label="适用课程" prop="parm">
<el-select
v-model="form.parm"
placeholder="请选择适用课程"
style="width: 100%"
>
<el-option
v-for="item in courseOptions"
:key="item.id"
:label="item.name"
:value="item.id"
/>
</el-select>
</el-form-item>
<script>
import {
getInnerCourseList,
// getAssociationList,
addOneActivityBounced,
editOneActivityBounced,
// uploadOneActivityImg,
} from '@/api/marketing/activityBounced'
import {
clubNoPage } from '@/api/common'
import {
ElMessage } from 'element-plus'
import {
ossFilePath } from '@/utils/ossFilePath'
import {
uploadPublicToAliOSS } from '@/api/common.js'
export default {
name: 'ActivityBouncedEdit',
emits: ['fetchData'],
data() {
return {
form: {
name: '',
mod: '1',
redirectType: '',
redirectUrl: '',
parm: '',
image: '',
startTime: '',
endTime: '',
},
courseOptions: [], //关联2-课程列表
associationOptions: [], //关联3-社团详情
params: {
}, //编辑传入参数==form+parm中整理对象
date: [], //起止时间
}
},
watch: {
'form.date'(val) {
if (val) {
if (val) {
this.form.startTime = val[0]
this.form.endTime = val[1]
} else {
this.form.startTime = this.form.endTime = ''
}
}
},
},
mounted() {
// 关联2 内部跳转-适合课程列表
// this.getCourseList()
// 关联3-社团详情-适用社团列表
// this.getAssocialList()
Promise.allSettled([this.getCourseList(), this.getAssocialList()])
.then((res) => {
this.courseOptions = res[0].value.result
this.associationOptions = res[1].value.result
})
.catch((err) => {
console.log('err:', err)
})
},
methods: {
close() {
this.$refs['form'].resetFields()
this.form = this.$options.data().form
this.dialogFormVisible = false
},
async getCourseList() {
return new Promise((resolve) => {
resolve(getInnerCourseList())
})
},
async getAssocialList() {
return new Promise((resolve) => {
// resolve(getAssociationList())
resolve(clubNoPage())
})
},
redirectTypeChange() {
this.form.parm = ''
this.form.redirectUrl = ''
},
},
}
</script>