SPA项目开发之首页导航+左侧菜单

SPA项目开发之首页导航+左侧菜单

1. Mock.js

前后端分离开发开发过程当中,经常会遇到以下几个尴尬的场景:
   1. 老大,接口文档还没输出,我的好多活干不下去啊!
   2. 后端小哥,接口写好了没,我要测试啊!
   前后端分离之后,前端迫切需要一种机制,不再需要依赖后端接口开发,而今天的主角mockjs就可以做到这一点

   Mock.js是一个模拟数据的生成器,用来帮助前端调试开发、进行前后端的原型分离以及用来提高自动化测试效率。

   众所周知Mock.js因为两个重要的特性风靡前端:
   数据类型丰富
   支持生成随机的文本、数字、布尔值、日期、邮箱、链接、图片、颜色等。
   拦截Ajax请求
   不需要修改既有代码,就可以拦截Ajax请求,返回模拟的响应数据。
   
   更多内容,可以云Mockjs官方查看“http://mockjs.com/”


   注1:easy-mock,一个在线模拟后台的数据平台

2. Mock.js使用步骤

2.1 安装mockjs依赖
      npm install mockjs -D              #只在开发环境使用

  2.2 引入
      为了只在开发环境使用mock,而打包到生产环境时自动不使用mock,我们可以在env中做一个配置
      (1)dev.env
      module.exports = merge(prodEnv, {
	NODE_ENV: '"development"',
  	MOCK: 'true'
      })
      
      (2)prod.env
      module.exports = {
	NODE_ENV: '"production"',
	MOCK: 'false'
      }

      (3)main.js
      //开发环境下才会引入mockjs
      process.env.MOCK && require('@/mock') 

      注1:import是ES6标准中的模块化解决方案,require是node中遵循CommonJS规范的模块化解决方案
          后者支持动态引入,也就是require(${path}/xx.js)
           2.3 目录和文件创建
      在src目录下创建mock目录,定义mock主文件index.js,并在该文件中定义拦截路由配置,
      /src/mock/index.js
      
      导入公共模块及mockjs全局设置
      import Mock from 'mockjs' //引入mockjs,npm已安装
      import action from '@/api/action' //引入封装的请求地址

      //全局设置:设置所有ajax请求的超时时间,模拟网络传输耗时
      Mock.setup({
	// timeout: 400  //延时400s请求到数据
	timeout: 200 - 400 //延时200-400s请求到数据
      })
       

      注1:index.js文件的作用很显然,就是将分散的xxx-mock文件集合起来.后面再添加新的mock文件,都需要在这里引入
        
            
  2.4 为每个*.vue定义单独的xxx-mock.js文件
      /src/mock/json/login-mock.js

      注1:可以添加自定义的json数据
      注2:还可以通过mockjs的模板生成随机数据
      
  2.5 在index.js中导入xxx-mock.js,并添加拦截路由配置
      import loginInfo from '@/mock/json/login-mock.js' 
      Mock.mock(url, "post", {...})
      2.6 之后ajax请求便会被mock拦截了

3. 使用this.$router.push({})实现路由跳转

3.1 字符串 
        this.$router.push('/home/first')

  3.2 对象 
      this.$router.push({ path: '/home/first' })

  3.3 命名的路由
        this.$router.push({ name: 'home', params: { userId: wise }})

  3.4 this.$router.push、replace、go的区别
        this.$router.push()
        跳转到不同的url,但这个方法会向history栈添加一个记录,点击后退会返回到上一个页面

        this.$router.replace()
        同样是跳转到指定的url,但是这个方法不会向history里面添加新的记录,点击返回,会跳转到上上一个页面。上一个记录是不存在的。

        this.$router.go(n)
        相对于当前页面向前或向后跳转多少个页面,类似 window.history.go(n)。n可为正数可为负数。负数返回上一个页面

4. 后台首页AppMain.vue的创建

2.1 Container布局容器

  2.2 TopNav
      
      注1:使用数据总线,在非父子的组件之间通信,完成左侧菜单折叠

  2.3 LeftNav

5. vue Bus总线

5.1 将一个空的Vue实例放到根组件下,所有的子组件都能调用
        main.js
        new Vue({
	el: '#app',
	router,
	components: {
		App
	},
	template: '<App/>',
	data: {
		//自定义的事件总线对象,用于父子组件的通信
		Bus: new Vue()
	}
         })

  5.2  在A组件触发事件
         this.$root.Bus.$emit("事件名", 参数1, 参数2, ...);

         注1:关键点-->this.$root
                  以前父子组件间触发事件是:this.$emit("事件名", 参数1, 参数2, ...);
              
  5.3 在B组件监听事件
        this.$root.Bus.$on("事件名", 回调函数);

好啦 现在直接上代码吧:
在这里插入图片描述
AppMain.vue:

<template>
	<el-container class="main-container">
		<el-aside v-bind:class="asideClass">
			<LeftNav></LeftNav>
		</el-aside>
		<el-container>
			<el-header class="main-header">
				<TopNav ></TopNav>
			</el-header>
			<el-main class="main-center">Main</el-main>
		</el-container>
	</el-container>
</template>

<script>
	// 导入组件
	import TopNav from '@/components/TopNav.vue'
	import LeftNav from '@/components/LeftNav.vue'

	// 导出模块
	export default {
		data(){
			return {
				asideClass:'main-aside'
			}
		},
		components:{
			TopNav,LeftNav
		},
		created(){
			this.$root.Bus.$on("collapsed-side",(v)=>{
				this.asideClass = v ? 'main-aside-collapsed ': 'main-aside';
			});
		}
	};
</script>
<style scoped>
	.main-container {
		height: 100%;
		width: 100%;
		box-sizing: border-box;
	}

	.main-aside-collapsed {
		/* 在CSS中,通过对某一样式声明! important ,可以更改默认的CSS样式优先级规则,使该条样式属性声明具有最高优先级 */
		width: 64px !important;
		height: 100%;
		background-color: #334157;
		margin: 0px;
	}

	.main-aside {
		width: 240px !important;
		height: 100%;
		background-color: #334157;
		margin: 0px;
	}

	.main-header,
	.main-center {
		padding: 0px;
		border-left: 2px solid #333;
	}
</style>


HelloWorld.vue:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>Essential Links</h2>
    <ul>
      <li>
        <a
          href="https://vuejs.org"
          target="_blank"
        >
          Core Docs
        </a>
      </li>
      <li>
        <a
          href="https://forum.vuejs.org"
          target="_blank"
        >
          Forum
        </a>
      </li>
      <li>
        <a
          href="https://chat.vuejs.org"
          target="_blank"
        >
          Community Chat
        </a>
      </li>
      <li>
        <a
          href="https://twitter.com/vuejs"
          target="_blank"
        >
          Twitter
        </a>
      </li>
      <br>
      <li>
        <a
          href="http://vuejs-templates.github.io/webpack/"
          target="_blank"
        >
          Docs for This Template
        </a>
      </li>
    </ul>
    <h2>Ecosystem</h2>
    <ul>
      <li>
        <a
          href="http://router.vuejs.org/"
          target="_blank"
        >
          vue-router
        </a>
      </li>
      <li>
        <a
          href="http://vuex.vuejs.org/"
          target="_blank"
        >
          vuex
        </a>
      </li>
      <li>
        <a
          href="http://vue-loader.vuejs.org/"
          target="_blank"
        >
          vue-loader
        </a>
      </li>
      <li>
        <a
          href="https://github.com/vuejs/awesome-vue"
          target="_blank"
        >
          awesome-vue
        </a>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>


LeftNav.vue:

<template>
	<el-menu default-active="2" class="el-menu-vertical-demo"  background-color="#334157"
	 text-color="#fff" active-text-color="#ffd04b" :collapse="collapsed" >
		<!-- <el-menu default-active="2" :collapse="collapsed" collapse-transition router :default-active="$route.path" unique-opened class="el-menu-vertical-demo" background-color="#334157" text-color="#fff" active-text-color="#ffd04b"> -->
		<div class="logobox">
			<img class="logoimg" src="../assets/img/logo.png" alt="">
		</div>
		<el-submenu index="1">
			<template slot="title">
				<i class="el-icon-location"></i>
				<span>导航一</span>
			</template>
			<el-menu-item-group>
				<template slot="title">分组一</template>
				<el-menu-item index="1-1">选项1</el-menu-item>
				<el-menu-item index="1-2">选项2</el-menu-item>
			</el-menu-item-group>
			<el-menu-item-group title="分组2">
				<el-menu-item index="1-3">选项3</el-menu-item>
			</el-menu-item-group>
			<el-submenu index="1-4">
				<template slot="title">选项4</template>
				<el-menu-item index="1-4-1">选项1</el-menu-item>
			</el-submenu>
		</el-submenu>
		<el-menu-item index="2">
			<i class="el-icon-menu"></i>
			<span slot="title">导航二</span>
		</el-menu-item>
		<el-menu-item index="3" disabled>
			<i class="el-icon-document"></i>
			<span slot="title">导航三</span>
		</el-menu-item>
		<el-menu-item index="4">
			<i class="el-icon-setting"></i>
			<span slot="title">导航四</span>
		</el-menu-item>
	</el-menu>
</template>
<script>
	export default {
		data(){
			return {
				collapsed:false
			}
		},
		created(){
			this.$root.Bus.$on("collapsed-side",(v)=>{
				this.collapsed = v;
			});
		}
	}
</script>
<style>
	.el-menu-vertical-demo:not(.el-menu--collapse) {
		width: 240px;
		min-height: 400px;
	}

	.el-menu-vertical-demo:not(.el-menu--collapse) {
		border: none;
		text-align: left;
	}

	.el-menu-item-group__title {
		padding: 0px;
	}

	.el-menu-bg {
		background-color: #1f2d3d !important;
	}

	.el-menu {
		border: none;
	}

	.logobox {
		height: 40px;
		line-height: 40px;
		color: #9d9d9d;
		font-size: 20px;
		text-align: center;
		padding: 20px 0px;
	}

	.logoimg {
		height: 40px;
	}
</style>


TopNav.vue:

<template>
	<!-- <el-menu :default-active="activeIndex2" class="el-menu-demo" mode="horizontal" @select="handleSelect" background-color="#545c64"
	 text-color="#fff" active-text-color="#ffd04b">
		<el-menu-item index="1">处理中心</el-menu-item>
		<el-submenu index="2">
			<template slot="title">我的工作台</template>
			<el-menu-item index="2-1">选项1</el-menu-item>
			<el-menu-item index="2-2">选项2</el-menu-item>
			<el-menu-item index="2-3">选项3</el-menu-item>
			<el-submenu index="2-4">
				<template slot="title">选项4</template>
				<el-menu-item index="2-4-1">选项1</el-menu-item>
				<el-menu-item index="2-4-2">选项2</el-menu-item>
				<el-menu-item index="2-4-3">选项3</el-menu-item>
			</el-submenu>
		</el-submenu>

		<el-menu-item index="3" disabled>消息中心</el-menu-item>
		<el-menu-item index="4"><a href="https://www.ele.me" target="_blank">订单管理</a></el-menu-item>
	</el-menu> -->
	<el-menu class="el-menu-demo" mode="horizontal" background-color="#334157" text-color="#fff" active-text-color="#fff">
		<el-button class="buttonimg">
			<img class="showimg" :src="collapsed?imgshow:imgsq" @click="doToggle()">
		</el-button>
		<el-submenu index="2" class="submenu">
			<template slot="title">超级管理员</template>
			<el-menu-item index="2-1">设置</el-menu-item>
			<el-menu-item index="2-2">个人中心</el-menu-item>
			<el-menu-item @click="exit()" index="2-3">退出</el-menu-item>
		</el-submenu>
	</el-menu>
</template>

<script>
	export default {
		data() {
			return {
				collapsed: false,
				imgshow: require('../assets/img/show.png'),
				imgsq: require('../assets/img/sq.png')
			}
		},
		methods:{
			exit(){
				this.$router.push({
					path:'/Login'
				})
			},
			doToggle(){
				this.collapsed =! this.collapsed;
				this.$root.Bus.$emit("collapsed-side",this.collapsed);
			}
		}
		
	}
</script>

<style scoped>
	.el-menu-vertical-demo:not(.el-menu--collapse) {
		border: none;
	}

	.submenu {
		float: right;
	}

	.buttonimg {
		height: 60px;
		background-color: transparent;
		border: none;
	}

	.showimg {
		width: 26px;
		height: 26px;
		position: absolute;
		top: 17px;
		left: 17px;
	}

	.showimg:active {
		border: none;
	}
</style>


index.js(mock):

import Mock from 'mockjs' //引入mockjs,npm已安装
import action from '@/api/action' //引入请求地址

//全局设置:设置所有ajax请求的超时时间,模拟网络传输耗时
Mock.setup({
	// timeout: 400  //延时400s请求到数据
	timeout: 200 - 400 //延时200-400s请求到数据
})

//引登陆的测试数据,并添加至mockjs
import loginInfo from '@/mock/json/login-mock.js'
let s1 = action.getFullPath('SYSTEM_USER_DOLOGIN')
Mock.mock(s1, "get", loginInfo)
// Mock.mock(s1, /post|get/i, loginInfo)


login-mock.js:

// const loginInfo = {
// 	code: -1,
// 	message: '密码错误'
// }

//使用mockjs的模板生成随机数据
const loginInfo = {
	'code|0-1': 0,
	'msg|3-10': 'msg'
}
export default loginInfo;


index.js(router):

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Login from '@/views/Login'
import Reg from '@/views/Reg'
import AppMain from '@/components/AppMain'
Vue.use(Router)

export default new Router({
	routes: [{
			path: '/',
			name: 'Login',
			component: Login
		},
		{
			path: '/Login',
			name: 'Login',
			component: Login
		},
		{
			path: '/Reg',
			name: 'Reg',
			component: Reg
		},
		{
			path: '/AppMain',
			name: 'AppMain',
			component: AppMain
		}
	]
})


Login.js:

<template>
	<div class="login-wrap">
		<el-form :model="ruleForm" class="demo-ruleForm login-container">
			<h3 style="text-align: center;"> 用户登录</h3>
			<el-form-item label="用户名">
				<el-input v-model="ruleForm.uname"></el-input>
			</el-form-item>
			<el-form-item label="密码">
				<el-input type="password" v-model="ruleForm.pwd"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button style="width: 100%;" type="primary" @click="doLogin()">提交</el-button>
			</el-form-item>
			<el-link type="primary">忘记密码</el-link>
			<el-link type="primary" @click="toReg">用户注册</el-link>
		</el-form>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				ruleForm: {
					uname: '',
					pwd: ''
				}
			};
		},
		methods: {
			toReg() {
				this.$router.push({
					path: '/Reg'
				})
			},
			doLogin() {
				let url = this.axios.urls.SYSTEM_USER_DOLOGIN;
				//get请求
				this.axios.get(url, {
					params: this.ruleForm
				}).then((response) => { //成功的回调函数
					console.log(response);
					if (response.data.code == 1) {
						this.$message({
							showClose: true,
							message: response.data.msg,
							type: 'success',
						});
						this.$router.push({
							path:'/AppMain'
						})
					} else {
						this.$message({
							showClose: true,
							message: response.data.msg,
							type: 'error'
						});
					}
				}).catch((response) => { //失败的回调函数(异常)
					console.log(response);
				});



				/* post请求 */
				/* qs.stringify()  将json转为键值对形式 */
				/* axios.post(url, qs.stringify(this.ruleForm)).then((response) =>{
					console.log(response);
					if (response.data.code == 1) {
						this.$message({
							showClose: true,
							message: response.data.msg,
							type: 'success'
						});
					} else {
						this.$message({
							showClose: true,
							message: response.data.msg,
							type: 'error'
						});
					}
				}).catch(function(error) {
					console.log(error);
				}); */
			}
		}
	}
</script>

<style scoped>
	.login-wrap {
		box-sizing: border-box;
		width: 100%;
		height: 100%;
		padding-top: 10%;
		background-image: url(data:image/svg+xml;
		
		background-color: #112346;
		background-repeat: no-repeat;
		background-position: center right;
		background-size: 100%;
	}

	.login-container {
		border-radius: 10px;
		margin: 0px auto;
		width: 350px;
		padding: 30px 35px 15px 35px;
		background: #fff;
		border: 1px solid #eaeaea;
		text-align: left;
		box-shadow: 0 0 20px 2px rgba(0, 0, 0, 0.1);
	}

	.title {
		margin: 0px auto 40px auto;
		text-align: center;
		color: #505458;
	}
</style>


main.js:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import 'element-ui/lib/theme-chalk/index.css'
process.env.MOCK && require('@/mock')
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import axios from '@/api/http' 
import VueAxios from 'vue-axios'


Vue.use(ElementUI) 
Vue.use(VueAxios,axios)
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
	el: '#app',
	data(){
		return {
			Bus:new Vue({
				
			})
		}
	},
	router,
	components: {
		App
	},
	template: '<App/>'
})


然后是效果图片:

在这里插入图片描述
上面这个是左侧菜单打开的展示效果图
在这里插入图片描述
上面的是左侧菜单收起的展示效果图。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值