Vue-08-实战快速上手

在人生的道路上,不管是潇洒走一回,或者是千山独行,皆须是自己想走的路,虽然,有的人并不是很快就能找到自己的方向和道路,不过,只要坚持到底,我相信,就一定可以找到自己的路,只要找到路,就不必怕路途遥远了。

导读:本篇文章讲解 Vue-08-实战快速上手,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

9.Vue:实战快速上手

  • 创建工程

  • 注意:命令行都要使用管理员模式运行

  • 创建一个名为hello-Vue的工程vue init webpack hello-vue

  • 安装依赖,我们需要安装vue-router、element-ui、sass-loader和node-sass四个插件

#进入工程目录
cd hello-vue
#安装Vue-router
cnpm install vue-router --save-dev
#安装element-ui
cnpm i element-ui -S
#安装依赖
npm install
#安装SASS加载器
cnpm install sass-loader node-sass --save-dev
#启动测试
npm run dev
  • Npm命令解释:

    • npm install moduleName:安装模块到项目目录下

    • npm instal1 -g moduleName:-g的意思是将模块安装到全局,具体安装到磁盘哪个位置,要看npm config prefix的位置

    • npm install -save moduleName:-save的意思是将模块安装到项目目录下,并在package文件的dependencies节点写入依赖,-S为该命令的缩写

    • npm install -save-dev moduleNam e:-save-deV的意思是将模块安装到项目目录下,并在package文件的devDependencies节点写入依赖,-D为该命令的缩写

  • components:放置功能组件

  • views:放视图组件

  • 创建views视图层目录,ViewMain.vue ,VueLogin.vue

<template>
<h2>首页</h2>
</template>

<script>
export default{
name: "VueMain",
}
</script>

<style>
</style>
<template>
<div>
<el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
<h3 class="login-title">欢迎 登录</h3>
<el-form-item label=" 账号" prop="username">
<el-input type="text" placeholder="请输入账号" v-model="form.username"/>
</el-form-item>
<el-form-item label=" 密码" prop="password">
<el-input type="password" placeholder=" 请输入密码" v-model="form.password"/>
</el-form-item>
<el-form-item>
<el-button type="primary" v-on:click="onSubmit( 'loginForm' )">登录</el-button>
</el-form-item>
</el-form>
<el-dialog
title="温馨提示"
:visible.sync="dialogVisible"
width="30%"
:before-close="handLeClose">
<span>请输入账号和密码</span>
<span slot="footer" class="dialog- footer">
<el-button type="primary" @click="dialogVisible = false">确定</el-button>
</span>
</el-dialog>
</div>
</template>

<script>
export default {
name: "VueLogin",
data() {
return {
form: {
  username: '',
  password: ''
},
//表单验证,需要在el-form-item 元素中增加prop 属性
rules: {
  username: [
	{required: true, message: " 账号不可为空", trigger: 'blur'}
  ],
  password: [
	{required: true, message: " 密码不可为空 ", trigger: 'blur'}
  ]
},
//对话框显示和隐藏
dialogVisible: false
}
},
methods: {
onSubmit(formName) {
//为表单绑定验证功能
this.$refs [formName].validate((valid) => {
  if (valid) {
	//使用vue-router路由到指定页面,该方式称之为编程式导航
	this.$router.push("/viewmain");
  } else {
	this.dialogVisible = true;
	return false;
  }
});
}
}
}
</script>

<style lang="scss" scoped>
.login-box {
border: 1px solid #DCDFE6;
width: 350px;
margin: 180px auto;
padding: 35px 35px 15px 35px;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
box-shadow: 0 0 25px #909399;
}

.login-title {
text-align: center;
margin: 0 auto 40px auto;
color: #303133;
}
</style>
  • 补充这两个视图组件的路由,上一节的导入和使用路由可以不要
import Vue from 'vue'
import VueRouter from 'vue-router'
import MyComment from '/src/components/MyComment.vue'
import MyMain from '/src/components/MyMain.vue'
import MyOther from '/src/components/MyOther.vue'
import ViewMain from '/src/views/ViewMain.vue'
import VueLogin from '/src/views/VueLogin.vue'
//安装路由
Vue.use(VueRouter)
//配置导出路由
export default new VueRouter({
	routes: [
		{
			//路径
			path: '/mycomment',
			name: 'mycomment',
			//跳转组件
			component: MyComment
		},
		{
			path: '/mymain',
			name: 'mymain',
			component: MyMain
		},
		{
			path: '/myother',
			name: 'myother',
			component: MyOther
		},
		{
			path: '/viewmain',
			name: 'viewmain',
			component: ViewMain
		},
		{
			path: '/vuelogin',
			name: 'vuelogin',
			component: VueLogin
		}
	]
})
  • 修改入口文件main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router/index' //自动扫描router/index.js的路由配置
import ElementUi from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUi)
Vue.config.productionTip = false
 new Vue({
el: '#app',
router,
render: h => h(App),    //element-ui定义规则
}).$mount('#app')
/* new Vue({
	el: '#app',
	router,
	components: {App},
	template: '<App/>'
}) */
  • 在App.vue中添加路径
<template>
<div id="app">
<router-link to="/mymain">首页</router-link>
<router-link to="/mycomment">内容</router-link>
<router-link to="/myother">其他</router-link>
<router-link to="/viewmain">elmentui首页</router-link>
<router-link to="/vuelogin">elmentui登录页</router-link>
<router-view></router-view>
</div>
</template>

<script>

export default {
  name: 'App'
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

  • 测试点击登录页,随便输入用户名、密码即可跳到首页,登录事件中设置了

在这里插入图片描述
在这里插入图片描述

  • 存在问题:

如果出现错误:可能是因为sass-loader的版本过高导致的编译错误,当前最高版本是8.x,需要退回到7.3.1;
去backage,json文件里面的”sass-loader’”的版本更换成7.3.1,然后重新cnpm install就可以了

将vue/cli版本降低为3.x,可以避免一些环境问题

9.1路由嵌套

  • 嵌套路由又称子路由,在实际应用中,通常由多层嵌套的组件组合而成。同样地,URL中各段动路径也按某种结构对应嵌套的各层组件,例如:
/user/foo/profile
/user/foo/posts
  • 用户信息组件,在views/user目录下创建一个名为Profile.vue的视图组件;

  • 在views下建user目录分别放置两个主页要显示的组件UserList.vue、UserProfile.vue

<template>
	<h1>用户信息</h1>
</template>

<script>
	export default{
	name: "UserProfile",
	}
</script>

<style>
</style>
<template>
	<h2>列表</h2>
</template>

<script>
	export default{
	name: "UserList",
	}
</script>

<style>
</style>
  • 之后再路由文件中配置这两个组件
import Vue from 'vue'
import VueRouter from 'vue-router'
import MyComment from '/src/components/MyComment.vue'
import MyMain from '/src/components/MyMain.vue'
import MyOther from '/src/components/MyOther.vue'
import ViewMain from '/src/views/ViewMain.vue'
import VueLogin from '/src/views/VueLogin.vue'
import UserList from '/src/views/user/UserList.vue'
import UserProfile from '/src/views/user//UserProfile.vue'
//安装路由
Vue.use(VueRouter)
//配置导出路由
export default new VueRouter({
	routes: [
		{
			//路径
			path: '/mycomment',
			name: 'mycomment',
			//跳转组件
			component: MyComment
		},
		{
			path: '/mymain',
			name: 'mymain',
			component: MyMain
		},
		{
			path: '/myother',
			name: 'myother',
			component: MyOther
		},
		{
			path: '/viewmain',
			name: 'viewmain',
			component: ViewMain,
			children:[
				{
					path: '/user/userlist',
					name: 'userlist',
					component: UserList
				},
				{
					path: '/user/userprofile',
					name: 'userprofile',
					component: UserProfile
				}
			]
		},
		{
			path: '/vuelogin',
			name: 'vuelogin',
			component: VueLogin
			
		}
		
	]
})
  • 不嵌套的话会打开新的标签页面

  • 修改views目录下的VueMian,是的主页框架出来

<template>
<div>
<el-container>
<el-aside width="200px">
<el-menu default-openeds="['1']">
<el-submenu index="1">
<template slot="title"><i class="el-icon-caret-right"></i>用户管理</template>
<el-menu-item-group>
<el-menu-item index="1-1">
<router-link to="/user/userprofile">个人信息</router-link>
</el-menu-item>
<el-menu-item index="1-2">
<router-link to="/user/userlist">用户列表</router-link>
</el-menu-item>
</el-menu-item-group>
</el-submenu>
<el-submenu index="2">
<template slot="title'"><i class:="el-icon-caret-right"></i>内容管理</template>
<el-menu-item-group>
<el-menu-item index="2-1">分类管理</el-menu-item>
<el-menu-item index:="2-2">内容列表</el-menu-item>
</el-menu-item-group>
</el-submenu>
</el-menu>
</el-aside>
<el-container>
<el-header style="text-align:right;font-size:12px">
<el-dropdown>
<i class="el-icon-setting" style="margin-right:15px"></i>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>个人信息</el-dropdown-item>
<el-dropdown-item>退出登录</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</el-header>
<el-main>
	<router-view></router-view>
</el-main>
</el-container>
</el-container>
</div>
</template>

<script>
export default{
name: "VueMain",
}
</script>

<style scoped lang="scss">
	.el-header{
		background-color: #d1cd8b;
		color: #333;
		line-height: 60px;
	}
	.el-aside{
		color: #333;
	}
</style>
  • 之后就可以测试了,登录后主页显示,由于elementui空间有一些问题,所以显示不完全,但嵌套路由效果也显示了
    在这里插入图片描述
    在这里插入图片描述

9.2 参数传递和重定向

  • 传递参数页:注意传参格式,显示用户信息
<template>
<div>
<el-container>
<el-aside width="200px">
<el-menu :default-openeds="['1']">
<el-submenu index="1">
<template slot="title"><i class="el-icon-caret-right"></i>用户管理</template>
<el-menu-item-group>
<el-menu-item index="1-1">
<router-link :to="{name:'userprofile',params:{id:1}}">个人信息</router-link>
</el-menu-item>
<el-menu-item index="1-2">
<router-link to="/user/userlist">用户列表</router-link>
</el-menu-item>
<el-menu-item index="1-3">
<router-link to="/gohome">回到首页</router-link>
</el-menu-item>
</el-menu-item-group>
</el-submenu>
<el-submenu index="2">
<template slot="title"><i class="el-icon-caret-right"></i>内容管理</template>
<e1-menu-item-group>
<el-menu-item index="2-1">分类管理</el-menu-item>
<el-menu-item index="2-2">内容列表</el-menu-item>
</e1-menu-item-group>
</el-submenu>
</el-menu>
</el-aside>
<el-container>
<el-header style="text-align: right; font-size: 12px;">
<el-dropdown>
<i class="el-icon-setting" style="margin-right: 15px;"></i>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>个人信息</el-dropdown-item>
<el-dropdown-item>退出登陆</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<span>{{name}}</span>
</el-header>
<el-main>
<router-view/>
</el-main>
</el-container>
</el-container>
</div>
</template>

<script>
export default{
props:['name'],
name: "VueMain",
}
</script>

<style scoped lang="scss">
	.el-header{
		background-color: #d1cd8b;
		color: #333;
		line-height: 60px;
	}
	.el-aside{
		color: #333;
	}
</style>
  • 路由页面配置index.js注意第二种方式需要在传递参数路径处加props:true,接受参数页才能通过props接受
import Vue from 'vue'
import VueRouter from 'vue-router'
import MyComment from '/src/components/MyComment.vue'
import MyMain from '/src/components/MyMain.vue'
import MyOther from '/src/components/MyOther.vue'
import ViewMain from '/src/views/ViewMain.vue'
import VueLogin from '/src/views/VueLogin.vue'
import UserList from '/src/views/user/UserList.vue'
import UserProfile from '/src/views/user//UserProfile.vue'
//安装路由
Vue.use(VueRouter)
//配置导出路由
export default new VueRouter({
	routes: [
		{
			//路径
			path: '/mycomment',
			name: 'mycomment',
			//跳转组件
			component: MyComment
		},
		{
			path: '/mymain',
			name: 'mymain',
			component: MyMain
		},
		{
			path: '/myother',
			name: 'myother',
			component: MyOther
		},
		{
			path: '/viewmain/:name',
			name: 'viewmain',
			component: ViewMain,
			props:true,
			children:[
				{
					path: '/user/userlist',
					name: 'userlist',
					component: UserList
				},
				{
					path: '/user/userprofile/:id',
					name: 'userprofile',
					component: UserProfile,
					props:true
				}
			]
		},
		{
			path: '/vuelogin',
			name: 'vuelogin',
			component: VueLogin
			
		},//上面都是转发,请求路径不变
		{
			path: '/gohome',
			redirect:'/mymain'
		}
		
	] 
})
  • 接受参数页UserProfile.vue,{{$router.params.id}}第一种方式失败,读取不到参数或ID
<template>
	<div>
	<!-- //所有元素需在根节点下 -->
	<h1>用户信息</h1>
	<!-- {{$router.params.id}} -->
	{{id}}
	</div>
</template>

<script>
	export default{
	props:['id'],
	name: "UserProfile",
	}
</script>

<style>
</style>
  • VueLogin页面传递用户信息
<template>
<div>
<el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
<h3 class="login-title">欢迎 登录</h3>
<el-form-item label=" 账号" prop="username">
<el-input type="text" placeholder="请输入账号" v-model="form.username"/>
</el-form-item>
<el-form-item label=" 密码" prop="password">
<el-input type="password" placeholder=" 请输入密码" v-model="form.password"/>
</el-form-item>
<el-form-item>
<el-button type="primary" v-on:click="onSubmit( 'loginForm' )">登录</el-button>
</el-form-item>
</el-form>
<el-dialog
title="温馨提示"
:visible.sync="dialogVisible"
width="30%"
:before-close="handLeClose">
<span>请输入账号和密码</span>
<span slot="footer" class="dialog- footer">
<el-button type="primary" @click="dialogVisible = false">确定</el-button>
</span>
</el-dialog>
</div>
</template>

<script>
export default {
name: "VueLogin",
data() {
return {
form: {
  username: '',
  password: ''
},
//表单验证,需要在el-form-item 元素中增加prop 属性
rules: {
  username: [
	{required: true, message: " 账号不可为空", trigger: 'blur'}
  ],
  password: [
	{required: true, message: " 密码不可为空 ", trigger: 'blur'}
  ]
},
//对话框显示和隐藏
dialogVisible: false
}
},
methods: {
onSubmit(formName) {
//为表单绑定验证功能
this.$refs [formName].validate((valid) => {
  if (valid) {
	//使用vue-router路由到指定页面,该方式称之为编程式导航
	this.$router.push("/viewmain/"+this.form.username);
  } else {
	this.dialogVisible = true;
	return false;
  }
})
}
}
}
</script>

<style lang="scss" scoped>
.login-box {
border: 1px solid #DCDFE6;
width: 350px;
margin: 180px auto;
padding: 35px 35px 15px 35px;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
box-shadow: 0 0 25px #909399;
}

.login-title {
text-align: center;
margin: 0 auto 40px auto;
color: #303133;
}
</style>
  • 重定向,需要在路由index配置重定向页面
{
    path: '/gohome',
    redirect:'/mymain'
 }

9.3 路由模式与404

  • 路由模式有两种
  • hash:路径带#符号,如http://localhost/#/login
  • history:路径不带#符号,如http://localhost/login修改路由配置,代码如下:
  • 修改路由配置,代码如下:
export default new Router({
mode:'history',
routes:
]
});
  • 前端部署到Nginx,通过Axios+Nignx的反向代理请求后端接口数据,这样分离部署的前后端就连起来了,不过这样还得解决跨域问题。

  • 404页面设置NotFound.vue

<template>
<div>
<span>404页面丢失</span>
</div>
</template>

<script>
export default{
name: "NotFound",
}
</script>

<style>
</style>
  • 路由配置
import NotFound from '/src/views/NotFound.vue'
{
path: '*',
component:NotFound
}

9.4 路由钩子与异步请求

  • beforeRouteEnter:在进入路由前执行
  • beforeRouteLeave:在离开路由前执行
<template>
	<div>
	<!-- //所有元素需在根节点下 -->
	<h1>用户信息</h1>
	<!-- {{$router.params.id}} -->
	{{id}}
	</div>
</template>

<script>
	export default{
	props:['id'],
	name: "UserProfile",
	//过滤器
	beforeRouteEnter :(to,from,next)=>{
		console.log(to+from+"进路由前")
		next()
	},
	beforeRouteLeave :(to,from,next)=>{
		console.log(to+from+"离开路由前")
		next()
	}
	}
</script>

<style>
</style>

  • 参数说明:

to:路由将要跳转的路径信息
from:路径跳转前的路径信息
next:路由的控制参数
next()跳入下一个页面
next(‘path)改变路由的跳转方向,使其跳到另一个路由

next(false)返回原来的页面
next(vm)=>)仅在beforeRouteEnter中可用,vm是组件实例,通过axios拉取数据

  • 在钩子函数中使用异步请求安装
  • Axios cnpm install axios -s/cnpm install vue-axios -s
  • main.js引用Axios
import Vue from 'vue'
import App from './App.vue'
import router from './router/index' //自动扫描router/index.js的路由配置
import ElementUi from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(ElementUi)
Vue.use(axios,VueAxios)
Vue.config.productionTip = false
 new Vue({
el: '#app',
router,
render: h => h(App),    //element-ui
}).$mount('#app')
/* new Vue({
	el: '#app',
	router,
	components: {App},
	template: '<App/>'
}) */
  • 在此static/mock/servicejs.json建个json文件
{
	"name":"zs",
	"url": "http://baidu.com",
	"address": {
	 "city":"北京"
    },
	"hower":[
		{"option":"java"},
		{"option":"python"},
		{"option":"c++"},
		{"option":"读书"}
	]
}
  • 在UserProfile.vue的路由钩子函数中使用异步请求数据
<template>
	<div>
	<!-- //所有元素需在根节点下 -->
	<h1>用户信息</h1>
	<!-- {{$router.params.id}} -->
	{{id}}
	</div>
</template>

<script>
	export default{
	props:['id'],
	name: "UserProfile",
	//过滤器
	beforeRouteEnter :(to,from,next)=>{
		console.log(to+from+"进路由前") //加载数据
		next(vm=>{
			vm.getData() //进入路由前执行getData
		})
	},
	beforeRouteLeave :(to,from,next)=>{
		console.log(to+from+"离开路由前")
		next()
	},
	methods:{
		getData:function(){
			this.axios(
		{
			method:'GET',
			url:'http://localhost:8082/static/mock/servicejs.json'
			}
			).
			then(response=>console.log(response.data()))
		}
	}
	}
</script>

<style>
</style>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/123874.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!