如何利用vue+vue-router+elementUI实现简易通讯录

2020-06-16 06:09:39易采站长站整理

<h3>我的应用</h3>
<template v-for="(item, index) in menuData">
<!-- 此处的index需显示转换为string,否则会报warn -->
<el-submenu :index="'' + (index + 1)">
<template slot="title">{{ item.name }}</template>
<template v-for="(subItem, i) in item.value">
<!-- 此处index格式为父级的index加上下划线加上当前的index,index都需加1 -->
<router-link tag="span" :to="subItem.path">
<el-menu-item :index="subItem.name">{{ subItem.title }}</el-menu-item>
</router-link>
</template>
</el-submenu>
</template>
</el-menu>
</el-col>
</el-row>
</div>
<div class="app-right">
<router-view></router-view>
</div>
</div>
</template>

<script>
import menuData from './config'

export default {
name: 'app',
data () {
return {
menuData,
menuIndex: '', // 菜单当前所在位置
menuUniqueOpen: true, // 菜单项是否唯一开启
menuRouter: true // 是否开启路由模式
}
},
mounted: function () {
...
},
watch: {
'$route' (to) {
this.menuIndex = to.name
}
}
}
</script>

这边偷了一个懒,没有把左侧的menu单独做成一个vue而是混入App.vue中。

6. 路由

在正式写代码之前,首先要确定要项目的结构,模块如何划分,哪个模块对应哪个路由。

因为整个项目现在就划分出两个大板块,通讯录与记账本,所以路由第一级就只有contact和account两种。


Vue.use(VueRouter)
let myRouter = new VueRouter({
routes: [
{
path: '*',
component: () => import('../components/NotFoundComponent.vue')
},
{
path: '/',
redirect: '/contact'
},
{
path: '/contact',
name: 'Contact',
component: () => import('../components/contact/List.vue')
},
{
path: '/contact/edit',
name: 'Contact',
component: () => import('../components/contact/Edit.vue')
},
{
path: '/account',
name: 'Account',
component: () => import('../components/account/list.vue')
}
]})

可以看到上面/contact和/contact/edit的name是相同的,这是为了让在新增或者编辑联系人页面下,还能让active状态停留在左侧我的联系人上,可以看到App.vue中的代码this.menuIndex = to.name就是进行的该操作,

虽然这样vue会报一个warn告诉我别重名[捂脸],暂时能想到的就是这样的操作方式了,有考虑过依靠判断path来确定是否显示高亮状态,但是当目录层级较深且较复杂的情况下,这样就不是很靠谱了。